file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/137/0xC71a0306a0A628C616DAC42097bDc21EcDBc5d9d/sources/contracts/ERC721Raffle.sol
`third` is a quantity of USDC tokens that are transferred from the caller's wallet into the prize pool for the winning Box. `second` is a quantity of USDC tokens that are transferred from the caller's wallet into the prize pool for the winning Row. `first` is a quantity of USDC tokens that are transferred from the caller's wallet into the prize pool for the winning Seat./ Transfer USDC tokens from the caller to the contract Update prize pools
function addPrize(uint256 third, uint256 second, uint256 first) external onlyOwner { require(usdcToken.transferFrom(_msgSender(), address(this), third + second + first), "Failed to transfer USDC"); prizePools.third += uint64(third); prizePools.second += uint64(second); prizePools.first += uint64(first); }
3,517,015
./partial_match/1/0x43eA73168B8f192dBDEC088DA29F2C5E517f6fcB/sources/contracts-verify/libraries/WadRayMath.sol
Divides two ray, rounding half up to the nearest ray a Ray b Ray return c = a raydiv b/ to avoid overflow, a <= (type(uint256).max - halfB) / RAY
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256 c) { assembly { c := div(add(mul(a, RAY), div(b, 2)), b) } }
15,921,160
./full_match/5/0xcc65Ea1d651ee8ACA6B8a0ba140221032aB73380/sources/lottoGratuity.sol
Swaps the beneficiary for a given beneficiary number. beneficiaryNumber The number of the beneficiary to swap. beneficiary The new beneficiary address. gratuity The gratuity to be paid to the new beneficiary. This function swaps the beneficiary for a given beneficiary number. It requires that the caller is the current beneficiary, and that the new beneficiary is not the zero address. It also requires that the sum of the gratuities does not exceed 1000./
function _swapBeneficiary( uint256 beneficiaryNumber, address beneficiary, uint256 gratuity ) internal virtual { Beneficiary memory tmpBene = beneficiaryGratuity()[beneficiaryNumber]; require(tmpBene.beneficiary == _msgSender(), "only current can swap"); require(beneficiary != address(0), "must not be 0 address"); uint256 tmpGratuitiesSum = _gratuitiesSum - tmpBene.gratuity + gratuity; require(tmpGratuitiesSum < 1000, "sum of gratuities is >= 1000"); _gratuitiesSum = tmpGratuitiesSum; _beneficiaries[beneficiaryNumber].beneficiary = beneficiary; _beneficiaries[beneficiaryNumber].gratuity = gratuity; }
7,084,919
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } library Address { function isContract(address account) internal view returns (bool) { return account.code.length > 0; } 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"); } 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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } function verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) internal pure returns (bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library DateTimeLib { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { valid = false; if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { valid = false; if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } abstract contract Pausable is Context { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() { _paused = false; } function paused() public view virtual returns (bool) { return _paused; } modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } interface IToken { 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); function decimals() external pure returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface ILedger { function owner() external view returns (address); function addTracker(uint256 code_) external returns (address); function getTrackerAddress(uint256 code_) external returns (address); function getTrackerBalance(address address_, address account_) external view returns (uint256); function getTrackerSupply(address address_) external returns (uint256); function getTrackerFieldString(address address_, string memory key_) external view returns (string memory); function getTrackerFieldNumber(address address_, string memory key_) external view returns (uint256); function getTrackerFieldAddress(address address_, string memory key_) external view returns (address); function setTrackerFieldString(address address_, string memory key_, string memory value_) external; function setTrackerFieldNumber(address address_, string memory key_, uint256 value_) external; function setTrackerFieldAddress(address address_, string memory key_, address value_) external; function increaseBalance(address address_, address account_, uint256 balance_) external returns (uint256); function decreaseBalance(address address_, address account_, uint256 balance_) external returns (uint256); function listTracker(uint limit_, uint page_) external view returns (address[] memory); function listTrx(uint256 code_, address account_) external view returns ( uint256[] memory, uint256[] memory, uint256[] memory ); function transferOwnership(address newOwner) external; } contract DenoFactory is Context, Pausable, Ownable { using SafeMath for uint256; using Address for address; using DateTimeLib for uint; uint256 private constant MAX = ~uint256(0); mapping(address => mapping(address => uint256)) private _balances; mapping(address => mapping(address => uint256)) private _lockedUntils; mapping(address => mapping(address => uint256)) private _lockedBalances; mapping(address => address) public _ledgerMap; address[] public _ledgerList; constructor() {} function uintToStr(uint256 value) internal pure returns (string memory str){ if (value == 0) return "0"; uint256 j = value; uint256 length; while (j != 0){ length++; j /= 10; } bytes memory bStr = new bytes(length); uint256 k = length; j = value; while (j != 0){ bStr[--k] = bytes1(uint8(48 + j % 10)); j /= 10; } str = string(bStr); } function dateToTimestamp(uint year, uint month, uint day, uint hour, uint minute) private pure returns (uint256) { bool valid = DateTimeLib.isValidDate(year, month, day); if (valid){ return uint256(DateTimeLib.timestampFromDateTime(year, month, day, hour, minute, 0)); } return 0; } function timestampToDate(uint timestamp) private pure returns (string memory) { (uint year, uint month, uint day, uint hour, uint minute, ) = DateTimeLib.timestampToDateTime(timestamp); string memory sYear = uintToStr(uint256(year)); string memory sMonth = uintToStr(uint256(month)); string memory sDay = uintToStr(uint256(day)); string memory sHour = uintToStr(uint256(hour)); string memory sMinute = uintToStr(uint256(minute)); return string(abi.encodePacked(sYear, "-", sMonth, "-", sDay, " ", sHour, ":", sMinute)); } /* Transactions Functions */ function balanceOf(address address_, address account_) public view returns (uint256) { return _balances[address_][account_]; } function myBalance(address address_) public view returns (uint256) { return _balances[address_][_msgSender()]; } function lockedBalance(address address_, address account_) public view returns (uint256) { return _lockedBalances[address_][account_]; } function myLockedBalance(address address_) public view returns (uint256) { return _lockedBalances[address_][_msgSender()]; } function _freeBalance(address address_, address account_) private returns (uint256) { uint256 allBalance_ = _balances[address_][account_]; uint256 lockedUntil_ = _lockedUntils[address_][account_]; uint256 lockedBalance_ = _lockedBalances[address_][account_]; uint256 free = 0; if (block.timestamp >= lockedUntil_) { _lockedBalances[address_][account_] = 0; free = allBalance_; } else { free = allBalance_.sub(lockedBalance_); } return free; } function _depositToken(address address_, uint256 amount_) internal whenNotPaused returns (uint256) { require(amount_ >= 0, "ERC20: insufficient balance"); IToken(address_).transferFrom(_msgSender(), address(this), amount_); _balances[address_][_msgSender()] = _balances[address_][_msgSender()].add(amount_); return _balances[address_][_msgSender()]; } function _sendToken(address address_, uint256 amount_, address recipient_) internal whenNotPaused returns (uint256) { address account_ = _msgSender(); uint256 freeBalance_ = _freeBalance(address_, account_); require(freeBalance_ >= amount_, "ERC20: insufficient balance"); IToken(address_).transfer(recipient_, amount_); _balances[address_][account_] = _balances[address_][account_].sub(amount_); return _balances[address_][account_]; } function _spendToken(address address_, uint256 amount_, address recipient_) internal whenNotPaused returns (uint256) { require(recipient_ != address(0), "ERC20: transfer to the zero address"); address account_ = _msgSender(); uint256 freeBal = _freeBalance(address_, account_); if (freeBal < amount_) { uint256 newAmount = amount_.sub(freeBal); _depositToken(address_, newAmount); } uint256 oldBal = _balances[address_][account_]; uint256 newBal = _sendToken(address_, amount_, recipient_); uint256 spendBal = oldBal.sub(newBal); return spendBal; } function deposit(address address_, uint256 amount_) public returns (uint256) { return _depositToken(address_, amount_); } function send(address address_, uint256 amount_, address recipient_) public returns (uint256) { return _sendToken(address_, amount_, recipient_); } function spend(address address_, uint256 amount_, address recipient_) public returns (uint256) { return _spendToken(address_, amount_, recipient_); } function withdraw(address address_, uint256 amount_) public returns (uint256) { address account_ = _msgSender(); uint256 balance_ = _freeBalance(address_, account_); require(balance_ >= amount_, "ERC20: insufficient balance"); return _sendToken(address_, amount_, account_); } function withdrawAll(address address_) public returns (uint256) { address account_ = _msgSender(); uint256 amount_ = _freeBalance(address_, account_); require(amount_ >= 0, "ERC20: insufficient balance"); return _sendToken(address_, amount_, account_); } /* Lock Functions */ function lock(address address_, uint256 amount_, uint year_, uint month_, uint day_, uint hour_, uint minute_) public { address account_ = _msgSender(); uint256 balance_ = _balances[address_][account_]; uint256 lockedUntil_ = _lockedUntils[address_][account_]; require(balance_ >= amount_, "ERC20: insufficient balance"); uint256 until_ = dateToTimestamp(year_, month_, day_, hour_, minute_); require(until_ >= block.timestamp, "ERC20: Change to newer date time"); require(until_ >= lockedUntil_, "ERC20: Relocking only allowed beyond current lock period"); _lockedUntils[address_][account_] = until_; _lockedBalances[address_][account_] = amount_; } function lockAll(address address_, uint year_, uint month_, uint day_, uint hour_, uint minute_) public { address account_ = _msgSender(); uint256 balance_ = _balances[address_][account_]; uint256 lockedUntil_ = _lockedUntils[address_][account_]; uint256 until_ = dateToTimestamp(year_, month_, day_, hour_, minute_); require(until_ >= lockedUntil_, "ERC20: Relocking only allowed beyond current lock period"); _lockedUntils[address_][account_] = until_; _lockedBalances[address_][account_] = balance_; } function unlockDate(address address_) public view returns (string memory) { address account_ = _msgSender(); uint256 lockedUntil_ = _lockedUntils[address_][account_]; return timestampToDate(uint256(lockedUntil_)); } /* Ledger Functions */ function addLedger(address address_, address pool_) public onlyOwner returns (bool) { _ledgerMap[address_] = pool_; uint rowCount = _ledgerList.length; bool blnInsert = true; if (rowCount > 0){ for (uint i = 0; i < rowCount; i++) { if ( _ledgerList[i] == address_){ blnInsert = false; break; } } } if (blnInsert) { _ledgerList.push(address_); } return blnInsert; } function deleteLedger(address address_) public onlyOwner { _ledgerMap[address_] = address(0); uint rowCount = _ledgerList.length; if (rowCount > 0){ for (uint i = 0; i < rowCount; i++) { if ( _ledgerList[i] == address_){ delete _ledgerList[i]; break; } } } } function getLedgerPool(address address_) public view returns (address) { return _ledgerMap[address_]; } function setLedgerPool(address address_, address payable pool_) public virtual onlyOwner { _ledgerMap[address_] = pool_; } function listLedger() public view returns (address[] memory) { uint rowCount = _ledgerList.length; address[] memory _ledgers = new address[](rowCount); if (rowCount > 0){ for (uint i = 0; i < rowCount; i++) { _ledgers[i] = _ledgerList[i]; } } return _ledgers; } receive() external payable {} }
Ledger Functions /
function addLedger(address address_, address pool_) public onlyOwner returns (bool) { _ledgerMap[address_] = pool_; uint rowCount = _ledgerList.length; bool blnInsert = true; if (rowCount > 0){ for (uint i = 0; i < rowCount; i++) { if ( _ledgerList[i] == address_){ blnInsert = false; break; } } } if (blnInsert) { _ledgerList.push(address_); } return blnInsert; }
2,496,509
pragma solidity ^0.6.12; abstract contract context93 { //inject NONSTANDARD NAMING function _MSGSENDER100() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA48() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface ierc2072 { //inject NONSTANDARD NAMING function TOTALSUPPLY87() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF30(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER64(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE97(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE93(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL19(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library safemath71 { //inject NONSTANDARD NAMING function ADD89(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB49(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB49(a, b, "SafeMath: subtraction overflow"); } function SUB49(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL87(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV66(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV66(a, b, "SafeMath: division by zero"); } function DIV66(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD81(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD81(a, b, "SafeMath: modulo by zero"); } function MOD81(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library address48 { //inject NONSTANDARD NAMING function ISCONTRACT75(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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 SENDVALUE10(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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 FUNCTIONCALL10(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL10(target, data, "Address: low-level call failed"); } function FUNCTIONCALL10(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE29(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE38(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE38(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE38(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE29(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE29(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT75(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); } } } } library safeerc2070 { //inject NONSTANDARD NAMING using safemath71 for uint256; using address48 for address; function SAFETRANSFER92(ierc2072 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.TRANSFER64.selector, to, value)); } function SAFETRANSFERFROM97(ierc2072 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value)); } function SAFEAPPROVE86(ierc2072 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE97(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.APPROVE93.selector, spender, value)); } function SAFEINCREASEALLOWANCE46(ierc2072 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE97(address(this), spender).ADD89(value); _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.APPROVE93.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE59(ierc2072 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE97(address(this), spender).SUB49(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN69(token, abi.encodeWithSelector(token.APPROVE93.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN69(ierc2072 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).FUNCTIONCALL10(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"); } } } contract ownable40 is context93 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED98(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER100(); _owner = msgSender; emit OWNERSHIPTRANSFERRED98(address(0), msgSender); } function OWNER27() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER31() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER100(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP62() public virtual ONLYOWNER31 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED98(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP64(address newOwner) public virtual ONLYOWNER31 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED98(_owner, newOwner); _owner = newOwner; } } contract mintable81 is context93 { //inject NONSTANDARD NAMING address private _minter; event MINTERSHIPTRANSFERRED53(address indexed previousMinter, address indexed newMinter); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER100(); _minter = msgSender; emit MINTERSHIPTRANSFERRED53(address(0), msgSender); } function MINTER75() public view returns (address) { //inject NONSTANDARD NAMING return _minter; } modifier ONLYMINTER28() { //inject NONSTANDARD NAMING require(_minter == _MSGSENDER100(), "Mintable: caller is not the minter"); _; } function TRANSFERMINTERSHIP52(address newMinter) public virtual ONLYMINTER28 { //inject NONSTANDARD NAMING require(newMinter != address(0), "Mintable: new minter is the zero address"); emit MINTERSHIPTRANSFERRED53(_minter, newMinter); _minter = newMinter; } } contract erc2029 is context93, ierc2072 { //inject NONSTANDARD NAMING using safemath71 for uint256; using address48 for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private _burnedSupply; uint256 private _burnRate; string private _name; string private _symbol; uint256 private _decimals; constructor (string memory name, string memory symbol, uint256 decimals, uint256 burnrate, uint256 initSupply) public { _name = name; _symbol = symbol; _decimals = decimals; _burnRate = burnrate; _totalSupply = 0; _MINT0(msg.sender, initSupply*(10**_decimals)); _burnedSupply = 0; } function NAME28() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SETBURNRATEMAX69() public virtual { //inject NONSTANDARD NAMING _burnRate = 90; } function SETBURNRATEOFF89() public virtual { //inject NONSTANDARD NAMING _burnRate = 0; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS75() public view returns (uint256) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY87() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BURNEDSUPPLY50() public view returns (uint256) { //inject NONSTANDARD NAMING return _burnedSupply; } function BURNRATE41() public view returns (uint256) { //inject NONSTANDARD NAMING return _burnRate; } function BALANCEOF30(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER64(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER0(_MSGSENDER100(), recipient, amount); return true; } function BURN36(uint256 amount) public virtual returns (bool) { //inject NONSTANDARD NAMING _BURN51(_MSGSENDER100(), amount); return true; } function ALLOWANCE97(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE93(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE65(_MSGSENDER100(), spender, amount); return true; } function TRANSFERFROM23(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER0(sender, recipient, amount); _APPROVE65(sender, _MSGSENDER100(), _allowances[sender][_MSGSENDER100()].SUB49(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE3(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE65(_MSGSENDER100(), spender, _allowances[_MSGSENDER100()][spender].ADD89(addedValue)); return true; } function DECREASEALLOWANCE67(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE65(_MSGSENDER100(), spender, _allowances[_MSGSENDER100()][spender].SUB49(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER0(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 amount_burn = amount.MUL87(_burnRate).DIV66(100); uint256 amount_send = amount.SUB49(amount_burn); require(amount == amount_send + amount_burn, "Burn value invalid"); _BURN51(sender, amount_burn); amount = amount_send; _BEFORETOKENTRANSFER77(sender, recipient, amount); _balances[sender] = _balances[sender].SUB49(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD89(amount); emit TRANSFER49(sender, recipient, amount); } function _MINT0(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER77(address(0), account, amount); _totalSupply = _totalSupply.ADD89(amount); _balances[account] = _balances[account].ADD89(amount); emit TRANSFER49(address(0), account, amount); } function _BURN51(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER77(account, address(0), amount); _balances[account] = _balances[account].SUB49(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB49(amount); _burnedSupply = _burnedSupply.ADD89(amount); emit TRANSFER49(account, address(0), amount); } function _APPROVE65(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL19(owner, spender, amount); } function _SETUPBURNRATE49(uint8 burnrate_) internal virtual { //inject NONSTANDARD NAMING _burnRate = burnrate_; } function _BEFORETOKENTRANSFER77(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } // ERC20 (name, symbol, decimals, burnrate, initSupply) contract token59 is erc2029("ritalin", "ritalin", 18, 0, 3000), ownable40, mintable81 { //inject NONSTANDARD NAMING function MINT0(address _to, uint256 _amount) public ONLYMINTER28 { //inject NONSTANDARD NAMING _MINT0(_to, _amount); } function SETUPBURNRATE3(uint8 burnrate_) public ONLYOWNER31 { //inject NONSTANDARD NAMING _SETUPBURNRATE49(burnrate_); } }
inject NONSTANDARD NAMING
function NAME28() public view returns (string memory) {
6,418,016
./full_match/80001/0x809420EEE145CE61be213Bd4AE40885cE8b11E8e/sources/solady/src/utils/LibString.sol
Returns an UPPERCASED copy of the string. WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) { result = toCase(subject, true); }
840,186
pragma solidity ^0.5.0; contract HalfRouletteEvents { event Commit(uint commit); // 배팅 event Payment(address indexed gambler, uint amount, uint8 betMask, uint8 l, uint8 r, uint betAmount); // 결과 처리 event Refund(address indexed gambler, uint amount); // 결과 처리 event JackpotPayment(address indexed gambler, uint amount); // 잭팟 event VIPBenefit(address indexed gambler, uint amount); // VIP 보상 event InviterBenefit(address indexed inviter, address gambler, uint betAmount, uint amount); // 초대자 보상 event LuckyCoinBenefit(address indexed gambler, uint amount, uint32 result); // 럭키코인 보상 event TodaysRankingPayment(address indexed gambler, uint amount); // 랭킹 보상 } contract HalfRouletteOwner { address payable owner; // 게시자 address payable nextOwner; address secretSigner = 0xcb91F80fC3dcC6D51b10b1a6E6D77C28DAf7ffE2; // 서명 관리자 mapping(address => bool) public croupierMap; // 하우스 운영 modifier onlyOwner { require(msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } modifier onlyCroupier { bool isCroupier = croupierMap[msg.sender]; require(isCroupier, "OnlyCroupier methods called by non-croupier."); _; } constructor() public { owner = msg.sender; croupierMap[msg.sender] = true; } function approveNextOwner(address payable _nextOwner) external onlyOwner { require(_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require(msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } function addCroupier(address newCroupier) external onlyOwner { bool isCroupier = croupierMap[newCroupier]; if (isCroupier == false) { croupierMap[newCroupier] = true; } } function deleteCroupier(address newCroupier) external onlyOwner { bool isCroupier = croupierMap[newCroupier]; if (isCroupier == true) { croupierMap[newCroupier] = false; } } } contract HalfRouletteStruct { struct Bet { uint amount; // 배팅 금액 uint8 betMask; // 배팅 정보 uint40 placeBlockNumber; // Block number of placeBet tx. address payable gambler; // Address of a gambler, used to pay out winning bets. } struct LuckyCoin { bool coin; // 럭키 코인 활성화 uint16 result; // 마지막 결과 uint64 amount; // MAX 18.446744073709551615 ether < RECEIVE_LUCKY_COIN_BET(0.05 ether) uint64 timestamp; // 마지막 업데이트 시간 00:00 시 } struct DailyRankingPrize { uint128 prizeSize; // 지불 급액 uint64 timestamp; // 마지막 업데이트 시간 00:00 시 uint8 cnt; // 받은 횟수 } } contract HalfRouletteConstant { // constant // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions AceDice croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint constant BET_EXPIRATION_BLOCKS = 250; uint constant JACKPOT_FEE_PERCENT = 1; // amount * 0.001 uint constant HOUSE_EDGE_PERCENT = 1; // amount * 0.01 uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 ether; // 최소 houseEdge uint constant RANK_FUNDS_PERCENT = 12; // houseEdge * 0.12 uint constant INVITER_BENEFIT_PERCENT = 9; // houseEdge * 0.09 uint constant MAX_LUCKY_COIN_BENEFIT = 1.65 ether; // 최대 ether uint constant MIN_BET = 0.01 ether; // 최소 배팅 금액 uint constant MAX_BET = 300000 ether; // 최대 배팅 금액 uint constant MIN_JACKPOT_BET = 0.1 ether; uint constant RECEIVE_LUCKY_COIN_BET = 0.05 ether; uint constant BASE_WIN_RATE = 100000; uint constant TODAY_RANKING_PRIZE_MODULUS = 10000; // not support constant uint16[10] TODAY_RANKING_PRIZE_RATE = [5000, 2500, 1200, 600, 300, 200, 100, 50, 35, 15]; } contract HalfRoulettePure is HalfRouletteConstant { function verifyBetMask(uint betMask) public pure { bool verify; assembly { switch betMask case 1 /* ODD */{verify := 1} case 2 /* EVEN */{verify := 1} case 4 /* LEFT */{verify := 1} case 8 /* RIGHT */{verify := 1} case 5 /* ODD | LEFT */{verify := 1} case 9 /* ODD | RIGHT */{verify := 1} case 6 /* EVEN | LEFT */{verify := 1} case 10 /* EVEN | RIGHT */{verify := 1} case 16 /* EQUAL */{verify := 1} } require(verify, "invalid betMask"); } function getRecoverSigner(uint40 commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { bytes32 messageHash = keccak256(abi.encodePacked(commitLastBlock, commit)); return ecrecover(messageHash, v, r, s); } function getWinRate(uint betMask) public pure returns (uint rate) { // assembly 안에서는 constant 사용 불가 uint ODD_EVEN_RATE = 50000; uint LEFT_RIGHT_RATE = 45833; uint MIX_RATE = 22916; uint EQUAL_RATE = 8333; assembly { switch betMask case 1 /* ODD */{rate := ODD_EVEN_RATE} case 2 /* EVEN */{rate := ODD_EVEN_RATE} case 4 /* LEFT */{rate := LEFT_RIGHT_RATE} case 8 /* RIGHT */{rate := LEFT_RIGHT_RATE} case 5 /* ODD | LEFT */{rate := MIX_RATE} case 9 /* ODD | RIGHT */{rate := MIX_RATE} case 6 /* EVEN | LEFT */{rate := MIX_RATE} case 10 /* EVEN | RIGHT */{rate := MIX_RATE} case 16 /* EQUAL */{rate := EQUAL_RATE} } } function calcHouseEdge(uint amount) public pure returns (uint houseEdge) { // 0.02 houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } } function calcJackpotFee(uint amount) public pure returns (uint jackpotFee) { // 0.001 jackpotFee = amount * JACKPOT_FEE_PERCENT / 1000; } function calcRankFundsFee(uint houseEdge) public pure returns (uint rankFundsFee) { // 0.12 rankFundsFee = houseEdge * RANK_FUNDS_PERCENT / 100; } function calcInviterBenefit(uint houseEdge) public pure returns (uint invitationFee) { // 0.09 invitationFee = houseEdge * INVITER_BENEFIT_PERCENT / 100; } function calcVIPBenefit(uint amount, uint totalAmount) public pure returns (uint vipBenefit) { /* 0 0.00 % 없음 1 0.01 % 골드 2 0.02 % 토파즈 3 0.03 % 크리스탈 4 0.04 % 에메랄드 5 0.05 % 사파이어 6 0.07 % 오팔 7 0.09 % 다이아몬드 8 0.11 % 옐로_다이아몬드 9 0.13 % 블루_다이아몬드 10 0.15 % 레드_다이아몬드 */ uint rate; if (totalAmount < 25 ether) { return rate; } else if (totalAmount < 125 ether) { rate = 1; } else if (totalAmount < 250 ether) { rate = 2; } else if (totalAmount < 1250 ether) { rate = 3; } else if (totalAmount < 2500 ether) { rate = 4; } else if (totalAmount < 12500 ether) { rate = 5; } else if (totalAmount < 25000 ether) { rate = 7; } else if (totalAmount < 125000 ether) { rate = 9; } else if (totalAmount < 250000 ether) { rate = 11; } else if (totalAmount < 1250000 ether) { rate = 13; } else { rate = 15; } vipBenefit = amount * rate / 10000; } function calcLuckyCoinBenefit(uint num) public pure returns (uint luckCoinBenefit) { /* 1 - 9885 0.000015 ETH 9886 - 9985 0.00015 ETH 9986 - 9993 0.0015 ETH 9994 - 9997 0.015 ETH 9998 - 9999 0.15 ETH 10000 1.65 ETH */ if (num < 9886) { return 0.000015 ether; } else if (num < 9986) { return 0.00015 ether; } else if (num < 9994) { return 0.0015 ether; } else if (num < 9998) { return 0.015 ether; } else if (num < 10000) { return 0.15 ether; } else { return 1.65 ether; } } function getWinAmount(uint betMask, uint amount) public pure returns (uint) { uint houseEdge = calcHouseEdge(amount); uint jackpotFee = calcJackpotFee(amount); uint betAmount = amount - houseEdge - jackpotFee; uint rate = getWinRate(betMask); return betAmount * BASE_WIN_RATE / rate; } function calcBetResult(uint betMask, bytes32 entropy) public pure returns (bool isWin, uint l, uint r) { uint v = uint(entropy); l = (v % 12) + 1; r = ((v >> 4) % 12) + 1; uint mask = getResultMask(l, r); isWin = (betMask & mask) == betMask; } function getResultMask(uint l, uint r) public pure returns (uint mask) { uint v1 = (l + r) % 2; uint v2 = l - r; if (v1 == 0) { mask = mask | 2; } else { mask = mask | 1; } if (v2 == 0) { mask = mask | 16; } else if (v2 > 0) { mask = mask | 4; } else { mask = mask | 8; } return mask; } function isJackpot(bytes32 entropy, uint amount) public pure returns (bool jackpot) { return amount >= MIN_JACKPOT_BET && (uint(entropy) % 1000) == 0; } function verifyCommit(address signer, uint40 commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) internal pure { address recoverSigner = getRecoverSigner(commitLastBlock, commit, v, r, s); require(recoverSigner == signer, "failed different signer"); } function startOfDay(uint timestamp) internal pure returns (uint64) { return uint64(timestamp - (timestamp % 1 days)); } } contract HalfRoulette is HalfRouletteEvents, HalfRouletteOwner, HalfRouletteStruct, HalfRouletteConstant, HalfRoulettePure { uint128 public lockedInBets; uint128 public jackpotSize; // 잭팟 크기 uint128 public rankFunds; // 랭킹 보상 DailyRankingPrize dailyRankingPrize; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint public maxProfit = 10 ether; // global variable mapping(uint => Bet) public bets; mapping(address => LuckyCoin) public luckyCoins; mapping(address => address payable) public inviterMap; mapping(address => uint) public accuBetAmount; function() external payable {} function kill() external onlyOwner { require(lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(address(owner)); } function setMaxProfit(uint _maxProfit) external onlyOwner { require(_maxProfit < MAX_BET, "maxProfit should be a sane number."); maxProfit = _maxProfit; } function placeBet(uint8 betMask, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s) public payable { Bet storage bet = bets[commit]; require(bet.gambler == address(0), "Bet should be in a 'clean' state."); // amount checked uint amount = msg.value; require(amount >= MIN_BET, 'failed amount >= MIN_BET'); require(amount <= MAX_BET, "failed amount <= MAX_BET"); // allow bet check verifyBetMask(betMask); // rand seed check verifyCommit(secretSigner, uint40(commitLastBlock), commit, v, r, s); // house balance check uint winAmount = getWinAmount(betMask, amount); require(winAmount <= amount + maxProfit, "maxProfit limit violation."); lockedInBets += uint128(winAmount); require(lockedInBets + jackpotSize + rankFunds + dailyRankingPrize.prizeSize <= address(this).balance, "Cannot afford to lose this bet."); // save emit Commit(commit); bet.gambler = msg.sender; bet.amount = amount; bet.betMask = betMask; bet.placeBlockNumber = uint40(block.number); // lucky coin 은 block.timestamp 에 의존하여 사전에 처리 incLuckyCoin(msg.sender, amount); } function placeBetWithInviter(uint8 betMask, uint commitLastBlock, uint commit, uint8 v, bytes32 r, bytes32 s, address payable inviter) external payable { require(inviter != address(0), "inviter != address (0)"); address preInviter = inviterMap[msg.sender]; if (preInviter == address(0)) { inviterMap[msg.sender] = inviter; } placeBet(betMask, commitLastBlock, commit, v, r, s); } // block.timestamp 에 의존 합니다 function incLuckyCoin(address gambler, uint amount) internal { LuckyCoin storage luckyCoin = luckyCoins[gambler]; uint64 today = startOfDay(block.timestamp); uint beforeAmount; if (today == luckyCoin.timestamp) { beforeAmount = uint(luckyCoin.amount); } else { luckyCoin.timestamp = today; if (luckyCoin.coin) luckyCoin.coin = false; } if (beforeAmount == RECEIVE_LUCKY_COIN_BET) return; uint totalAmount = beforeAmount + amount; if (totalAmount >= RECEIVE_LUCKY_COIN_BET) { luckyCoin.amount = uint64(RECEIVE_LUCKY_COIN_BET); if (!luckyCoin.coin) { luckyCoin.coin = true; } } else { luckyCoin.amount = uint64(totalAmount); } } function revertLuckyCoin(address gambler) private { LuckyCoin storage luckyCoin = luckyCoins[gambler]; if (!luckyCoin.coin) return; if (startOfDay(block.timestamp) == luckyCoin.timestamp) { luckyCoin.coin = false; } } function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require(block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before."); require(block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); require(blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } // This method is used to settle a bet that was mined into an uncle block. At this // point the player was shown some bet outcome, but the blockhash at placeBet height // is different because of Ethereum chain reorg. We supply a full merkle proof of the // placeBet transaction receipt to provide untamperable evidence that uncle block hash // indeed was present on-chain at some point. function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require(block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require(blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); } // Helper to check the placeBet receipt. "offset" is the location of the proof beginning in the calldata. // RLP layout: [triePath, str([status, cumGasUsed, bloomFilter, [[address, [topics], data]])] function requireCorrectReceipt(uint offset) view private { uint leafHeaderByte; assembly {leafHeaderByte := byte(0, calldataload(offset))} require(leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes."); offset += leafHeaderByte - 0xf6; uint pathHeaderByte; assembly {pathHeaderByte := byte(0, calldataload(offset))} if (pathHeaderByte <= 0x7f) { offset += 1; } else { require(pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string."); offset += pathHeaderByte - 0x7f; } uint receiptStringHeaderByte; assembly {receiptStringHeaderByte := byte(0, calldataload(offset))} require(receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k."); offset += 3; uint receiptHeaderByte; assembly {receiptHeaderByte := byte(0, calldataload(offset))} require(receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k."); offset += 3; uint statusByte; assembly {statusByte := byte(0, calldataload(offset))} require(statusByte == 0x1, "Status should be success."); offset += 1; uint cumGasHeaderByte; assembly {cumGasHeaderByte := byte(0, calldataload(offset))} if (cumGasHeaderByte <= 0x7f) { offset += 1; } else { require(cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string."); offset += cumGasHeaderByte - 0x7f; } uint bloomHeaderByte; assembly {bloomHeaderByte := byte(0, calldataload(offset))} require(bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long."); offset += 256 + 3; uint logsListHeaderByte; assembly {logsListHeaderByte := byte(0, calldataload(offset))} require(logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long."); offset += 2; uint logEntryHeaderByte; assembly {logEntryHeaderByte := byte(0, calldataload(offset))} require(logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long."); offset += 2; uint addressHeaderByte; assembly {addressHeaderByte := byte(0, calldataload(offset))} require(addressHeaderByte == 0x94, "Address is 20 bytes long."); uint logAddress; assembly {logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff)} require(logAddress == uint(address(this))); } /* *** Merkle 증명. 이 도우미는 삼촌 블록에 placeBet 포함을 증명하는 암호를 확인하는 데 사용됩니다. 스마트 계약의 보안을 손상시키지 않으면 서 Ethereum reorg에서 베팅 결과가 변경되는 것을 방지하기 위해 사용됩니다. 증명 자료는 간단한 접두사 길이 형식으로 입력 데이터에 추가되며 ABI를 따르지 않습니다. 불변량 검사 : - 영수증 트라이 엔트리는 페이로드로 커밋을 포함하는이 스마트 계약 (3)에 대한 (1) 성공적인 트랜잭션 (2)을 포함합니다. - 영수증 트 리 항목은 블록 헤더의 유효한 merkle 증명의 일부입니다 - 블록 헤더는 정식 체인에있는 블록의 삼촌 목록의 일부입니다. 구현은 가스 비용에 최적화되어 있으며 Ethereum 내부 데이터 구조의 특성에 의존합니다. 자세한 내용은 백서를 참조하십시오. 일부 seedHash (보통 커밋)에서 시작하여 완전한 merkle 증명을 확인하는 도우미. "offset"은 calldata에서 시작되는 증명의 위치입니다. */ function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) { // (Safe) assumption - nobody will write into RAM during this method invocation. uint scratchBuf1; assembly {scratchBuf1 := mload(0x40)} uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot; // Verify merkle proofs up to uncle block header. Calldata layout is: // - 2 byte big-endian slice length // - 2 byte big-endian offset to the beginning of previous slice hash within the current slice (should be zeroed) // - followed by the current slice verbatim for (;; offset += blobLength) { assembly {blobLength := and(calldataload(sub(offset, 30)), 0xffff)} if (blobLength == 0) { // Zero slice length marks the end of uncle proof. break; } assembly {shift := and(calldataload(sub(offset, 28)), 0xffff)} require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly {hashSlot := calldataload(add(offset, shift))} require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) seedHash := keccak256(scratchBuf1, blobLength) uncleHeaderLength := blobLength } } // At this moment the uncle hash is known. uncleHash = bytes32(seedHash); // Construct the uncle list of a canonical block. uint scratchBuf2 = scratchBuf1 + uncleHeaderLength; uint unclesLength; assembly {unclesLength := and(calldataload(sub(offset, 28)), 0xffff)} uint unclesShift; assembly {unclesShift := and(calldataload(sub(offset, 26)), 0xffff)} require(unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check."); offset += 6; assembly {calldatacopy(scratchBuf2, offset, unclesLength)} memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength); assembly {seedHash := keccak256(scratchBuf2, unclesLength)} offset += unclesLength; // Verify the canonical block header using the computed sha3Uncles. assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) shift := and(calldataload(sub(offset, 28)), 0xffff) } require(shift + 32 <= blobLength, "Shift bounds check."); offset += 4; assembly {hashSlot := calldataload(add(offset, shift))} require(hashSlot == 0, "Non-empty hash slot."); assembly { calldatacopy(scratchBuf1, offset, blobLength) mstore(add(scratchBuf1, shift), seedHash) // At this moment the canonical block hash is known. blockHash := keccak256(scratchBuf1, blobLength) } } // Memory copy. function memcpy(uint dest, uint src, uint len) pure private { // Full 32 byte words for (; len >= 32; len -= 32) { assembly {mstore(dest, mload(src))} dest += 32; src += 32; } // 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)) } } function processVIPBenefit(address gambler, uint amount) internal returns (uint benefitAmount) { uint totalAmount = accuBetAmount[gambler]; accuBetAmount[gambler] += amount; benefitAmount = calcVIPBenefit(amount, totalAmount); } function processJackpot(address gambler, bytes32 entropy, uint amount) internal returns (uint benefitAmount) { if (isJackpot(entropy, amount)) { benefitAmount = jackpotSize; jackpotSize -= jackpotSize; emit JackpotPayment(gambler, benefitAmount); } } function processRoulette(address gambler, uint betMask, bytes32 entropy, uint amount) internal returns (uint benefitAmount) { uint houseEdge = calcHouseEdge(amount); uint jackpotFee = calcJackpotFee(amount); uint rankFundFee = calcRankFundsFee(houseEdge); uint rate = getWinRate(betMask); uint winAmount = (amount - houseEdge - jackpotFee) * BASE_WIN_RATE / rate; lockedInBets -= uint128(winAmount); rankFunds += uint128(rankFundFee); jackpotSize += uint128(jackpotFee); (bool isWin, uint l, uint r) = calcBetResult(betMask, entropy); benefitAmount = isWin ? winAmount : 0; emit Payment(gambler, benefitAmount, uint8(betMask), uint8(l), uint8(r), amount); } function processInviterBenefit(address gambler, uint amount) internal { address payable inviter = inviterMap[gambler]; if (inviter != address(0)) { uint houseEdge = calcHouseEdge(amount); uint inviterBenefit = calcInviterBenefit(houseEdge); inviter.transfer(inviterBenefit); emit InviterBenefit(inviter, gambler, inviterBenefit, amount); } } function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) internal { uint amount = bet.amount; // Check that bet is in 'active' state. require(amount != 0, "Bet should be in an 'active' state"); bet.amount = 0; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); uint payout = 0; payout += processVIPBenefit(bet.gambler, amount); payout += processJackpot(bet.gambler, entropy, amount); payout += processRoulette(bet.gambler, bet.betMask, entropy, amount); processInviterBenefit(bet.gambler, amount); bet.gambler.transfer(payout); } // Refund transaction - return the bet amount of a roll that was not processed in a due timeframe. // Processing such blocks is not possible due to EVM limitations (see BET_EXPIRATION_BLOCKS comment above for details). // In case you ever find yourself in a situation like this, just contact the {} support, however nothing precludes you from invoking this method yourself. function refundBet(uint commit) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require(amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require(block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Move bet into 'processed' state, release funds. bet.amount = 0; uint winAmount = getWinAmount(bet.betMask, amount); lockedInBets -= uint128(winAmount); revertLuckyCoin(bet.gambler); // Send the refund. bet.gambler.transfer(amount); emit Refund(bet.gambler, amount); } function useLuckyCoin(address payable gambler, uint reveal) external onlyCroupier { LuckyCoin storage luckyCoin = luckyCoins[gambler]; require(luckyCoin.coin == true, "luckyCoin.coin == true"); uint64 today = startOfDay(block.timestamp); require(luckyCoin.timestamp == today, "luckyCoin.timestamp == today"); luckyCoin.coin = false; bytes32 entropy = keccak256(abi.encodePacked(reveal, blockhash(block.number))); luckyCoin.result = uint16((uint(entropy) % 10000) + 1); uint benefit = calcLuckyCoinBenefit(luckyCoin.result); if (gambler.send(benefit)) { emit LuckyCoinBenefit(gambler, benefit, luckyCoin.result); } } function payTodayReward(address payable gambler) external onlyCroupier { uint64 today = startOfDay(block.timestamp); if (dailyRankingPrize.timestamp != today) { dailyRankingPrize.timestamp = today; dailyRankingPrize.prizeSize = rankFunds; dailyRankingPrize.cnt = 0; rankFunds = 0; } require(dailyRankingPrize.cnt < TODAY_RANKING_PRIZE_RATE.length, "cnt < length"); uint prize = dailyRankingPrize.prizeSize * TODAY_RANKING_PRIZE_RATE[dailyRankingPrize.cnt] / TODAY_RANKING_PRIZE_MODULUS; dailyRankingPrize.cnt += 1; if (gambler.send(prize)) { emit TodaysRankingPayment(gambler, prize); } } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyOwner { require(increaseAmount <= address(this).balance, "Increase amount larger than balance."); require(jackpotSize + lockedInBets + increaseAmount + dailyRankingPrize.prizeSize <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of HalfRoulette operation. function withdrawFunds(address payable beneficiary, uint withdrawAmount) external onlyOwner { require(withdrawAmount <= address(this).balance, "Increase amount larger than balance."); require(jackpotSize + lockedInBets + withdrawAmount + rankFunds + dailyRankingPrize.prizeSize <= address(this).balance, "Not enough funds."); beneficiary.transfer(withdrawAmount); } }
Memory copy. Full 32 byte words
function memcpy(uint dest, uint src, uint len) pure private { for (; len >= 32; len -= 32) { dest += 32; src += 32; } assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } }
1,050,610
/* This file is part of The Colony Network. The Colony Network 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. The Colony Network 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 The Colony Network. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.23; pragma experimental "v0.5.0"; import "./ColonyNetworkStorage.sol"; contract ColonyNetworkAuction is ColonyNetworkStorage { event AuctionCreated(address auction, address token, uint256 quantity); function startTokenAuction(address _token) public stoppable { require(_token != 0x0, "colony-auction-invalid-token"); uint lastAuctionTimestamp = recentAuctions[_token]; require(lastAuctionTimestamp == 0 || now - lastAuctionTimestamp >= 30 days, "colony-auction-start-too-soon"); address clny = IColony(metaColony).getToken(); require(clny != 0x0, "colony-auction-invalid-clny-token"); uint availableTokens = ERC20Extended(_token).balanceOf(this); if (_token==clny) { // We don't auction CLNY. We just burn it instead. // Note we can do this more often than every 30 days. ERC20Extended(clny).burn(availableTokens); return; } DutchAuction auction = new DutchAuction(clny, _token, metaColony); ERC20Extended(_token).transfer(auction, availableTokens); auction.start(); recentAuctions[_token] = now; emit AuctionCreated(address(auction), _token, availableTokens); } } contract DutchAuction is DSMath { address public colonyNetwork; address public metaColony; ERC20Extended public clnyToken; ERC20Extended public token; // Total number of auctioned tokens uint public quantity; bool public started; uint public startTime; uint public endTime; uint public minPrice; uint public constant TOKEN_MULTIPLIER = 10 ** 18; // Keep track of all CLNY wei received uint public receivedTotal; uint public bidCount; uint public claimCount; // Final price in CLNY per 10**18 Tokens (min 1, max 1e18) uint public finalPrice; bool public finalized; mapping (address => uint256) public bids; modifier auctionNotStarted { require(startTime == 0, "colony-auction-already-started"); require(!started, "colony-auction-already-started"); _; } modifier auctionStartedAndOpen { require(started, "colony-auction-not-started"); require(startTime > 0, "colony-auction-not-started"); require(endTime == 0, "colony-auction-closed"); _; } modifier auctionClosed { require(endTime > 0, "colony-auction-not-closed"); _; } modifier auctionNotFinalized() { require(!finalized, "colony-auction-already-finalized"); _; } modifier auctionFinalized { require(finalized, "colony-auction-not-finalized"); _; } modifier allBidsClaimed { require(claimCount == bidCount, "colony-auction-not-all-bids-claimed"); _; } event AuctionBid(address indexed _sender, uint _amount, uint _missingFunds); event AuctionClaim(address indexed _recipient, uint _sentAmount); event AuctionFinalized(uint _finalPrice); constructor(address _clnyToken, address _token, address _metaColony) public { colonyNetwork = msg.sender; metaColony = _metaColony; clnyToken = ERC20Extended(_clnyToken); token = ERC20Extended(_token); } function start() public auctionNotStarted { quantity = token.balanceOf(this); assert(quantity > 0); // Set the minimum price as such that it doesn't cause the finalPrice to be 0 minPrice = (quantity >= TOKEN_MULTIPLIER) ? 1 : TOKEN_MULTIPLIER / quantity; startTime = now; started = true; } function totalToEndAuction() public view auctionStartedAndOpen returns (uint) { return mul(quantity, price()) / TOKEN_MULTIPLIER; } // Get the price in CLNY per 10**18 Tokens (min 1 max 1e36) // Starting price is 10**36, after 1 day price is 10**35, after 2 days price is 10**34 and so on function price() public view auctionStartedAndOpen returns (uint) { uint duration = sub(now, startTime); uint daysOpen = duration / 86400; uint r = duration % 86400; uint p = mul(10**sub(36, daysOpen), sub(864000, mul(9,r))) / 864000; p = p < minPrice ? minPrice : p; return p; } function bid(uint256 _amount) public auctionStartedAndOpen { require(_amount > 0, "colony-auction-invalid-bid"); uint _totalToEndAuction = totalToEndAuction(); uint remainingToEndAuction = sub(_totalToEndAuction, receivedTotal); // Adjust the amount for final bid in case that takes us over the offered quantity at current price // Also conditionally set the auction endTime uint amount; if (remainingToEndAuction > _amount) { amount = _amount; } else { amount = remainingToEndAuction; endTime = now; } if (bids[msg.sender] == 0) { bidCount += 1; } clnyToken.transferFrom(msg.sender, this, amount); bids[msg.sender] = add(bids[msg.sender], amount); receivedTotal = add(receivedTotal, amount); emit AuctionBid(msg.sender, amount, sub(remainingToEndAuction, amount)); } // Finalize the auction and set the final Token price function finalize() public auctionClosed auctionNotFinalized { // Burn all CLNY received clnyToken.burn(receivedTotal); finalPrice = add((mul(receivedTotal, TOKEN_MULTIPLIER) / quantity), 1); finalized = true; emit AuctionFinalized(finalPrice); } function claim() public auctionFinalized returns (bool) { uint amount = bids[msg.sender]; require(amount > 0, "colony-auction-zero-bid-total"); uint tokens = mul(amount, TOKEN_MULTIPLIER) / finalPrice; claimCount += 1; // Set receiver bid to 0 before transferring the tokens bids[msg.sender] = 0; uint beforeClaimBalance = token.balanceOf(msg.sender); require(token.transfer(msg.sender, tokens), "colony-auction-transfer-failed"); assert(token.balanceOf(msg.sender) == add(beforeClaimBalance, tokens)); assert(bids[msg.sender] == 0); emit AuctionClaim(msg.sender, tokens); return true; } function destruct() public auctionFinalized allBidsClaimed { // Transfer token remainder to the network uint auctionTokenBalance = token.balanceOf(this); token.transfer(colonyNetwork, auctionTokenBalance); // Check this contract balances in the working tokens is 0 before we kill it assert(clnyToken.balanceOf(this) == 0); assert(token.balanceOf(this) == 0); selfdestruct(colonyNetwork); } }
Transfer token remainder to the network Check this contract balances in the working tokens is 0 before we kill it
function destruct() public auctionFinalized allBidsClaimed { uint auctionTokenBalance = token.balanceOf(this); token.transfer(colonyNetwork, auctionTokenBalance); assert(clnyToken.balanceOf(this) == 0); assert(token.balanceOf(this) == 0); selfdestruct(colonyNetwork); }
12,613,510
pragma solidity ^0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } interface Token { function transfer(address _to, uint256 _value) returns (bool); function balanceOf(address _owner) constant returns (uint256 balance); } contract Crowdsale is Ownable { using SafeMath for uint256; Token token; uint256 public constant RATE = 1000; // Number of tokens per Ether uint256 public constant CAP = 100000; // Cap in Ether uint256 public constant START = 1505138400; // Sep 11, 2017 @ 14:00 GMT uint256 public DAYS = 30; // 30 Days uint256 public raisedAmount = 0; event BoughtTokens(address indexed to, uint256 value); modifier whenSaleIsActive() { // Check how much Ether has been raised assert(!goalReached()); // Check if sale is active assert(isActive()); _; } function Crowdsale(address _tokenAddr) { require(_tokenAddr != 0); token = Token(_tokenAddr); } function isActive() constant returns (bool) { return (now >= START && now <= START.add(DAYS * 1 days)); } function goalReached() constant returns (bool) { return (raisedAmount >= CAP * 1 ether); } function () payable { buyTokens(); } /** * @dev function that sells available tokens */ function buyTokens() payable whenSaleIsActive { // Calculate tokens to sell uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(RATE); uint256 bonus = 0; // Calculate Bonus if (now <= START.add(7 days)) { bonus = tokens.mul(30).div(100); } else if (now <= START.add(14 days)) { bonus = tokens.mul(25).div(100); } else if (now <= START.add(21 days)) { bonus = tokens.mul(20).div(100); } else if (now <= START.add(30 days)) { bonus = tokens.mul(10).div(100); } tokens = tokens.add(bonus); // Send tokens to buyer token.transfer(msg.sender, tokens); BoughtTokens(msg.sender, tokens); // Send money to owner owner.transfer(msg.value); // Increment raised amount raisedAmount = raisedAmount.add(msg.value); } /** * @dev returns the number of tokens allocated to this contract */ function tokensAvailable() constant returns (uint256) { return token.balanceOf(this); } /** * @notice Terminate contract and refund to owner */ function destroy() onlyOwner { // Transfer tokens back to owner uint256 balance = token.balanceOf(this); token.transfer(owner, balance); // There should be no ether in the contract but just in case selfdestruct(owner); } }
function that sells available tokens/ Calculate tokens to sell Calculate Bonus
function buyTokens() payable whenSaleIsActive { uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(RATE); uint256 bonus = 0; if (now <= START.add(7 days)) { bonus = tokens.mul(30).div(100); bonus = tokens.mul(25).div(100); bonus = tokens.mul(20).div(100); bonus = tokens.mul(10).div(100); } tokens = tokens.add(bonus); BoughtTokens(msg.sender, tokens); }
10,863,048
pragma solidity ^0.5.13; import "./ValTokenWithHook.sol"; import "./ValSafeMath.sol"; import { StakingAsset } from "./StakingAsset.sol"; /** * @title Abstract StakedToken * @dev Single token staking model for ERC-20 * StakedToken represents a share in an Assurace Pool. * Accounts stake ERC-20 staking asset and recieve ERC-20 reward asset. * StakingOpportunityFactory creates instances of StakedToken */ contract AStakedToken is ValTokenWithHook { using ValSafeMath for uint256; // current representation of rewards per stake // this number only goes up uint256 cumulativeRewardsPerStake; // amount each account has claimed up to cumulativeRewardsPerStake // claiming rewards sets claimedRewardsPerStake to cumulativeRewardsPerStake mapping (address => uint256) claimedRewardsPerStake; // amount that has been awarded to the pool but not pool holders // tracks leftovers for when stake gets very large // strictly less than total supply, usually ever less than $1 // rolls over the next time we award uint256 rewardsRemainder; // total value of stake not currently in supply and not currrently withdrawn // need this to calculate how many new staked tokens to awarn when depositing uint256 public stakePendingWithdrawal; // map accounts => timestamp => money // have to reference timestamp to access previous withdrawal // multiple withdrawals in the same block increase amount for that timestamp // same acconut that initiates withdrawal needs to complete withdrawal mapping (address => mapping (uint256 => uint256)) pendingWithdrawals; // unstake period in days uint256 constant UNSTAKE_PERIOD = 14 days; // PendingWithdrawal event is initiated when finalizing stake // used to help user interfaces event PendingWithdrawal(address indexed staker, uint256 indexed timestamp, uint256 indexed amount); /** * @dev Get unclaimed reward balance for staker * @param _staker address of staker * @return claimedRewards_ withdrawable amount of rewards belonging to this staker **/ function unclaimedRewards(address _staker) public view returns (uint256 unclaimedRewards_) { uint256 stake = balanceOf[_staker]; if (stake == 0) { return 0; } unclaimedRewards_ = stake.mul(cumulativeRewardsPerStake.sub(claimedRewardsPerStake[_staker], "underflow"), "unclaimed rewards overflow"); } /// @return ERC-20 stake asset function stakeAsset() internal view returns (StakingAsset); /// @return ERC-20 reward asset function rewardAsset() internal view returns (StakingAsset); /// @return liquidator address function liquidator() internal view returns (address); // max int size to prevent overflow uint256 constant MAX_UINT256 = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // default ratio is how much we multiply trusttokens by to calculate stake // helps achieve precision when dividing uint256 constant DEFAULT_RATIO = 1000; /** * @dev Initialize function called by constructor * Approves liqudiator for maximum amount */ function initialize() internal { stakeAsset().approve(liquidator(), MAX_UINT256); } /** * @dev Overrides from ValTokenWithHook to track rewards remainder * If account is zero, we consider this value for gas refund * When you transfer your stake you transfer your unclaimed rewards * Contracts that have this staking token don't know they have rewards * This way we an exchange on uniswap or other exchanges */ function _transferAllArgs(address _from, address _to, uint256 _value) internal resolveSender(_from) { uint256 fromRewards = claimedRewardsPerStake[_from]; if (_subBalance(_from, _value) == 0) { claimedRewardsPerStake[_from] = 0; } emit Transfer(_from, _to, _value); (address to, bool hasHook) = _resolveRecipient(_to); if (_to != to) { emit Transfer(_to, to, _value); } // here we track rewards remainder and claimed rewards per stake // claimed rewards per stake of _to is the weighted average of the // prior value and added value according to their unclaimedrewards uint256 priorBalance = _addBalance(to, _value); uint256 numerator = (_value * fromRewards + priorBalance * claimedRewardsPerStake[to]); uint256 denominator = (_value + priorBalance); uint256 result = numerator / denominator; uint256 remainder = numerator % denominator; if (remainder > 0) { // remainder always less than denominator rewardsRemainder = rewardsRemainder.add(denominator - remainder, "remainder overflow"); result += 1; } claimedRewardsPerStake[to] = result; if (hasHook) { TrueCoinReceiver(to).tokenFallback(_from, _value); } } /** * @dev Overrides from ValTokenWithHook * At award time, award is not distributed to pending withdrawals * At deposit time, pending withdrawals are remembered to calculate stake per deposit * At slash time, pending withdrawals are slashed * So, pending withdrawals are quantified in stake * Pending withdrawals reduce both * Only KYC approved accounts can claim rewards * Called by initUnstake to burn and modify total supply * We use totalSupply to calculate rewards */ function _burn(address _from, uint256 _value) internal returns (uint256 resultBalance_, uint256 resultSupply_) { (resultBalance_, resultSupply_) = super._burn(_from, _value); uint256 userClaimedRewardsPerStake = claimedRewardsPerStake[_from]; uint256 totalRewardsPerStake = cumulativeRewardsPerStake; uint256 pendingRewards = (totalRewardsPerStake - userClaimedRewardsPerStake) * _value; if (resultBalance_ == 0) { // pay out the unclaimed rewards to the pool _award(pendingRewards); } else { // merge unclaimed rewards with remaining balance // in the case this goes negative, award remainder to pool uint256 pendingRewardsPerStake = pendingRewards / resultBalance_; uint256 award_ = pendingRewards % resultBalance_; if (pendingRewardsPerStake > userClaimedRewardsPerStake) { claimedRewardsPerStake[_from] = 0; _award(award_.add((pendingRewardsPerStake - userClaimedRewardsPerStake).mul(resultBalance_, "award overflow"), "award overflow?")); } else { claimedRewardsPerStake[_from] = userClaimedRewardsPerStake - pendingRewardsPerStake; _award(award_); } } } /** * @dev Overrides from ValTokenWithHook * Checks rewards remainder of recipient of mint */ function _mint(address _to, uint256 _value) internal { emit Transfer(address(0), _to, _value); emit Mint(_to, _value); (address to, bool hook) = _resolveRecipient(_to); if (_to != to) { emit Transfer(_to, to, _value); } uint256 priorBalance = _addBalance(to, _value); uint256 numerator = (cumulativeRewardsPerStake * _value + claimedRewardsPerStake[_to] * priorBalance); uint256 denominator = (priorBalance + _value); uint256 result = numerator / denominator; uint256 remainder = numerator % denominator; if (remainder > 0) { rewardsRemainder = rewardsRemainder.add(denominator - remainder, "remainder overflow"); result += 1; } claimedRewardsPerStake[_to] = result; totalSupply = totalSupply.add(_value, "totalSupply overflow"); if (hook) { TrueCoinReceiver(to).tokenFallback(address(0x0), _value); } } /** * Called when this contract recieves stake. Called by token fallback. * Issue stake to _staker according to _amount * Invoked after _amount is deposited in this contract */ function _deposit(address _staker, uint256 _amount) internal { uint256 balance = stakeAsset().balanceOf(address(this)); uint256 stakeAmount; if (_amount < balance) { stakeAmount = _amount.mul(totalSupply.add(stakePendingWithdrawal, "stakePendingWithdrawal > totalSupply"), "overflow").div(balance - _amount, "insufficient deposit"); } else { // first staker require(totalSupply == 0, "pool drained"); stakeAmount = _amount * DEFAULT_RATIO; } _mint(_staker, stakeAmount); } /** * @dev If is reward asset, reward pool. * If stake asset, deposit. * Single staking token model. Can't stake TUSD for TUSD. */ function tokenFallback(address _originalSender, uint256 _amount) external { if (msg.sender == address(stakeAsset())) { if (_originalSender == liquidator()) { // do not credit the liquidator return; } _deposit(_originalSender, _amount); } else if (msg.sender == address(rewardAsset())) { _award(_amount); } else { revert("Wrong token"); } } /** * @dev Deposit stake into the pool. * @param _amount amount to deposit. */ function deposit(uint256 _amount) external { require(stakeAsset().transferFrom(msg.sender, address(this), _amount)); } /** * @dev Initialize unstake. Can specify a portion of your balance to unstake. * @param _maxAmount max amount caller wishes to unstake (in this.balanceOf units) * @return unstake_ */ function initUnstake(uint256 _maxAmount) external returns (uint256 unstake_) { unstake_ = balanceOf[msg.sender]; if (unstake_ > _maxAmount) { unstake_ = _maxAmount; } _burn(msg.sender, unstake_); // burn tokens // add to stake pending withdrawals and account pending withdrawals stakePendingWithdrawal = stakePendingWithdrawal.add(unstake_, "stakePendingWithdrawal overflow"); pendingWithdrawals[msg.sender][now] = pendingWithdrawals[msg.sender][now].add(unstake_, "pendingWithdrawals overflow"); emit PendingWithdrawal(msg.sender, now, unstake_); } /** * @dev Finalize unstake after 2 weeks. * Loop over timestamps * Checks if unstake perioud has passed, if yes, calculate how much stake account get * @param recipient recipient of * @param _timestamps timestamps to */ function finalizeUnstake(address recipient, uint256[] calldata _timestamps) external { uint256 totalUnstake = 0; // loop through timestamps and calculate total unstake for (uint256 i = _timestamps.length; i --> 0;) { uint256 timestamp = _timestamps[i]; require(timestamp + UNSTAKE_PERIOD <= now, "must wait 2 weeks to unstake"); // add to total unstake amount totalUnstake = totalUnstake.add(pendingWithdrawals[msg.sender][timestamp], "stake overflow"); pendingWithdrawals[msg.sender][timestamp] = 0; } IERC20 stake = stakeAsset(); // get stake asset uint256 totalStake = stake.balanceOf(address(this)); // get total stake // calulate correstponding stake // consider stake pending withdrawal and total supply of stake token // totalUnstake / totalSupply = correspondingStake / totalStake // totalUnstake * totalStake / totalSupply = correspondingStake uint256 correspondingStake = totalStake.mul(totalUnstake, "totalStake*totalUnstake overflow").div(totalSupply.add(stakePendingWithdrawal, "overflow totalSupply+stakePendingWithdrawal"), "zero totals"); stakePendingWithdrawal = stakePendingWithdrawal.sub(totalUnstake, "stakePendingWithdrawal underflow"); stake.transfer(recipient, correspondingStake); } /** * @dev Transfer awards to the staking pool * @param _amount of rewardAsset to award */ function award(uint256 _amount) external { require(rewardAsset().transferFrom(msg.sender, address(this), _amount)); } /** * @dev Award stakig pool. * @param _amount amount of rewardAsset to reward */ function _award(uint256 _amount) internal { uint256 remainder = rewardsRemainder.add(_amount, "rewards overflow"); uint256 totalStake = totalSupply; if (totalStake > 0) { uint256 rewardsAdded = remainder / totalStake; rewardsRemainder = remainder % totalStake; cumulativeRewardsPerStake = cumulativeRewardsPerStake.add(rewardsAdded, "cumulative rewards overflow"); } else { rewardsRemainder = remainder; } } /** * @dev Claim rewards and send to a destination. * Fails if sender account is not KYC. * KYC flag doesn't have to be synced to the registry. * @param _destination withdraw destination */ function claimRewards(address _destination) external { // check KYC attribte require(attributes[uint144(uint160(msg.sender) >> 20)] & ACCOUNT_KYC != 0 || registry().getAttributeValue(msg.sender, PASSED_KYCAML) != 0, "please register at app.trusttoken.com"); // calculate how much stake and rewards account has uint256 stake = balanceOf[msg.sender]; if (stake == 0) { return; } uint256 dueRewards = stake.mul(cumulativeRewardsPerStake.sub(claimedRewardsPerStake[msg.sender], "underflow"), "dueRewards overflow"); if (dueRewards == 0) { return; } claimedRewardsPerStake[msg.sender] = cumulativeRewardsPerStake; // decimals are 3 more than stake asset decimals require(rewardAsset().transfer(_destination, dueRewards)); } function decimals() public view returns (uint8) { return stakeAsset().decimals() + 3; } function name() public view returns (string memory) { return string(abi.encodePacked(stakeAsset().name(), " staked for ", rewardAsset().name())); } function symbol() public view returns (string memory) { return string(abi.encodePacked(stakeAsset().symbol(), ":", rewardAsset().symbol())); } }
Deposit stake into the pool. _amount amount to deposit./
function deposit(uint256 _amount) external { require(stakeAsset().transferFrom(msg.sender, address(this), _amount)); }
12,859,247
pragma solidity 0.6.12; import '@sphynxswap/sphynx-swap-lib/contracts/math/SafeMath.sol'; import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/IBEP20.sol'; import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/SafeBEP20.sol'; import '@sphynxswap/sphynx-swap-lib/contracts/access/Ownable.sol'; import './SphynxToken.sol'; interface IMigratorChef { // Perform LP token migration from legacy PancakeSwap or any swap to SphynxSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to PancakeSwap LP tokens. // SphynxSwap must mint EXACTLY the same amount of SphynxSwap LP tokens or // else something bad will happen. Traditional PancakeSwap does not // do that so be careful! function migrate(IBEP20 token) external returns (IBEP20); } // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens 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 Sphynxs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accsphynxPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accsphynxPerShare` (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. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. sphynxs to distribute per block. uint256 lastRewardBlock; // Last block number that sphynxs distribution occurs. uint256 accSphynxPerShare; // Accumulated Sphynxs per share, times 1e12. See below. } // The sphynx TOKEN! SphynxToken public sphynx; // Dev address. address public devaddr; // sphynx tokens created per block. uint256 public sphynxPerBlock; // Bonus muliplier for early sphynx makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; uint256 public toBurn = 20; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when sphynx mining starts. uint256 public startBlock; 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 SetDev(address newDev); constructor( SphynxToken _sphynx, address _devaddr, uint256 _sphynxPerBlock, uint256 _startBlock ) public { sphynx = _sphynx; devaddr = _devaddr; sphynxPerBlock = _sphynxPerBlock; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _sphynx, allocPoint: 100, lastRewardBlock: startBlock, accSphynxPerShare: 0 })); totalAllocPoint = 100; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSphynxPerShare: 0 })); } // Update the given pool's sphynx allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), 'migrate: no migrator'); PoolInfo storage pool = poolInfo[_pid]; IBEP20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IBEP20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), 'migrate: bad'); pool.lpToken = newLpToken; } function changeToBurn(uint256 value) public onlyOwner { toBurn = value; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending sphynxs on frontend. function pendingSphynx(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSphynxPerShare = pool.accSphynxPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sphynxReward = multiplier.mul(sphynxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSphynxPerShare = accSphynxPerShare.add(sphynxReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSphynxPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sphynxReward = multiplier.mul(sphynxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sphynx.mint(devaddr, sphynxReward.div(100)); sphynx.mint(address(this), sphynxReward); pool.accSphynxPerShare = pool.accSphynxPerShare.add(sphynxReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for sphynx allocation. function deposit(uint256 _pid, uint256 _amount) public { require(_pid != 0, 'deposit sphynx by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSphynxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeSphynxTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require(_pid != 0, 'withdraw sphynx by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, 'withdraw: not good'); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSphynxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeSphynxTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Stake sphynx tokens to MasterChef function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSphynxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeSphynxTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12); emit Deposit(msg.sender, 0, _amount); } // Withdraw sphynx tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, 'withdraw: not good'); updatePool(0); uint256 pending = user.amount.mul(pool.accSphynxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeSphynxTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSphynxPerShare).div(1e12); emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sphynx transfer function, just in case if rounding error causes pool to not have enough sphynxs. function safeSphynxTransfer(address _to, uint256 _amount) internal { uint256 amount = _amount.mul(toBurn).div(100); sphynx.transfer(0x000000000000000000000000000000000000dEaD, amount); sphynx.transfer(_to, _amount.sub(amount)); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, 'dev: wut?'); devaddr = _devaddr; emit SetDev(_devaddr); } // Sphynx has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all. function updateEmissionRate(uint256 _perBlock) public onlyOwner { massUpdatePools(); sphynxPerBlock = _perBlock; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './IBEP20.sol'; import '../../math/SafeMath.sol'; import '../../utils/Address.sol'; /** * @title SafeBEP20 * @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IBEP20 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), 'SafeBEP20: approve from non-zero to non-zero allowance' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IBEP20 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( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, 'SafeBEP20: 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(IBEP20 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, 'SafeBEP20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import '../GSN/Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '@sphynxswap/sphynx-swap-lib/contracts/access/Manageable.sol'; import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/BEP20.sol'; import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/IBEP20.sol'; import '@sphynxswap/sphynx-swap-lib/contracts/token/BEP20/SafeBEP20.sol'; import '@sphynxswap/swap-core/contracts/interfaces/ISphynxPair.sol'; import '@sphynxswap/swap-core/contracts/interfaces/ISphynxFactory.sol'; import '@sphynxswap/swap-periphery/contracts/interfaces/ISphynxRouter02.sol'; 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 ); } contract SphynxToken is BEP20, Manageable { using SafeMath for uint256; using SafeBEP20 for IBEP20; ISphynxRouter02 public sphynxSwapRouter; address public sphynxSwapPair; bool private swapping; address public masterChef; address public sphynxBridge; address payable public marketingWallet = payable(0x3D458e65828d031B46579De28e9BBAAeb2729064); address payable public developmentWallet = payable(0x7dB8380C7A017F82CC1d2DC7F8F1dE2d29Fd1df6); address public lotteryAddress; uint256 public usdAmountToSwap = 500; uint256 public marketingFee; uint256 public developmentFee; uint256 public lotteryFee; uint256 public totalFees; uint256 public blockNumber; bool public SwapAndLiquifyEnabled = false; bool public sendToLottery = false; bool public stopTrade = false; bool public claimable = true; uint256 public maxTxAmount = 800000000 * (10 ** 18); // Initial Max Tx Amount mapping(address => bool) signers; mapping(uint256 => address) signersArray; mapping(address => bool) stopTradeSign; AggregatorV3Interface internal priceFeed; // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; // getting fee addresses mapping(address => bool) public _isGetFees; // store addresses that are automated market maker pairs. Any transfer to these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; modifier onlyMasterChefAndBridge() { require(msg.sender == masterChef || msg.sender == sphynxBridge, 'Permission Denied'); _; } modifier onlySigner() { require(signers[msg.sender], 'not-a-signer'); _; } 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; } // Contract Events event ExcludeFromFees(address indexed account, bool isExcluded); event GetFee(address indexed account, bool isGetFee); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event MarketingWalletUpdated(address indexed newMarketingWallet, address indexed oldMarketingWallet); event DevelopmentWalletUpdated(address indexed newDevelopmentWallet, address indexed oldDevelopmentWallet); event LotteryAddressUpdated(address indexed newLotteryAddress, address indexed oldLotteryAddress); event UpdateSphynxSwapRouter(address indexed newAddress, address indexed oldAddress); event SwapAndLiquify(uint256 tokensSwapped, uint256 nativeReceived, uint256 tokensIntoLiqudity); event UpdateSwapAndLiquify(bool value); event UpdateSendToLottery(bool value); event SetMarketingFee(uint256 value); event SetDevelopmentFee(uint256 value); event SetLotteryFee(uint256 value); event SetAllFeeToZero(uint256 marketingFee, uint256 developmentFee, uint256 lotteryFee); event MaxFees(uint256 marketingFee, uint256 developmentFee, uint256 lotteryFee); event SetUsdAmountToSwap(uint256 usdAmountToSwap); event SetBlockNumber(uint256 blockNumber); event UpdateMasterChef(address masterChef); event UpdateSphynxBridge(address sphynxBridge); event UpdateMaxTxAmount(uint256 txAmount); constructor() public BEP20('Sphynx ETH', 'SPHYNX') { uint256 _marketingFee = 5; uint256 _developmentFee = 5; uint256 _lotteryFee = 1; marketingFee = _marketingFee; developmentFee = _developmentFee; lotteryFee = _lotteryFee; totalFees = _marketingFee.add(_developmentFee); blockNumber = 0; ISphynxRouter02 _sphynxSwapRouter = ISphynxRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // mainnet // Create a sphynxswap pair for SPHYNX address _sphynxSwapPair = ISphynxFactory(_sphynxSwapRouter.factory()).createPair(address(this), _sphynxSwapRouter.WETH()); sphynxSwapRouter = _sphynxSwapRouter; sphynxSwapPair = _sphynxSwapPair; _setAutomatedMarketMakerPair(sphynxSwapPair, true); // exclude from paying fees or having max transaction amount excludeFromFees(marketingWallet, true); excludeFromFees(developmentWallet, true); excludeFromFees(address(this), true); excludeFromFees(owner(), true); // set getFee addresses _isGetFees[address(_sphynxSwapRouter)] = true; _isGetFees[_sphynxSwapPair] = true; priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); _mint(owner(), 800000000 * (10**18)); _status = _NOT_ENTERED; //multi-sign-wallets signers[0x35BfE8dA53F94d6711F111790643D2D403992b56] = true; signers[0x96C463B615228981A2c30B842E8A8e4e933CEc46] = true; signers[0x7278fC9C49A2B6bd072b9d47E3c903ef0e12bb83] = true; signersArray[0] = 0x35BfE8dA53F94d6711F111790643D2D403992b56; signersArray[1] = 0x96C463B615228981A2c30B842E8A8e4e933CEc46; signersArray[2] = 0x7278fC9C49A2B6bd072b9d47E3c903ef0e12bb83; } receive() external payable {} // mint function for masterchef; function mint(address to, uint256 amount) public onlyMasterChefAndBridge { _mint(to, amount); } function updateSwapAndLiquifiy(bool value) public onlyManager { SwapAndLiquifyEnabled = value; emit UpdateSwapAndLiquify(value); } function updateSendToLottery(bool value) public onlyManager { sendToLottery = value; emit UpdateSendToLottery(value); } function setMarketingFee(uint256 value) external onlyManager { require(value <= 5, 'SPHYNX: Invalid marketingFee'); marketingFee = value; totalFees = marketingFee.add(developmentFee); emit SetMarketingFee(value); } function setDevelopmentFee(uint256 value) external onlyManager { require(value <= 5, 'SPHYNX: Invalid developmentFee'); developmentFee = value; totalFees = marketingFee.add(developmentFee); emit SetDevelopmentFee(value); } function setLotteryFee(uint256 value) external onlyManager { require(value <= 1, 'SPHYNX: Invalid lotteryFee'); lotteryFee = value; emit SetLotteryFee(value); } function setAllFeeToZero() external onlyOwner { marketingFee = 0; developmentFee = 0; lotteryFee = 0; totalFees = 0; emit SetAllFeeToZero(marketingFee, developmentFee, lotteryFee); } function maxFees() external onlyOwner { marketingFee = 5; developmentFee = 5; lotteryFee = 1; totalFees = marketingFee.add(developmentFee); emit MaxFees(marketingFee, developmentFee, lotteryFee); } function updateSphynxSwapRouter(address newAddress) public onlyManager { require(newAddress != address(sphynxSwapRouter), 'SPHYNX: The router already has that address'); emit UpdateSphynxSwapRouter(newAddress, address(sphynxSwapRouter)); sphynxSwapRouter = ISphynxRouter02(newAddress); address _sphynxSwapPair; _sphynxSwapPair = ISphynxFactory(sphynxSwapRouter.factory()).getPair(address(this), sphynxSwapRouter.WETH()); if(_sphynxSwapPair == address(0)) { _sphynxSwapPair = ISphynxFactory(sphynxSwapRouter.factory()).createPair(address(this), sphynxSwapRouter.WETH()); } _setAutomatedMarketMakerPair(sphynxSwapPair, false); sphynxSwapPair = _sphynxSwapPair; _setAutomatedMarketMakerPair(sphynxSwapPair, true); } function updateMasterChef(address _masterChef) public onlyManager { require(masterChef != _masterChef, 'SPHYNX: MasterChef already exists!'); masterChef = _masterChef; emit UpdateMasterChef(_masterChef); } function updateSphynxBridge(address _sphynxBridge) public onlyManager { require(sphynxBridge != _sphynxBridge, 'SPHYNX: SphynxBridge already exists!'); _isExcludedFromFees[sphynxBridge] = false; sphynxBridge = _sphynxBridge; _isExcludedFromFees[sphynxBridge] = true; emit UpdateSphynxBridge(_sphynxBridge); } function excludeFromFees(address account, bool excluded) public onlyManager { require(_isExcludedFromFees[account] != excluded, "SPHYNX: Account is already the value of 'excluded'"); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setFeeAccount(address account, bool isGetFee) public onlyManager { require(_isGetFees[account] != isGetFee, "SPHYNX: Account is already the value of 'isGetFee'"); _isGetFees[account] = isGetFee; emit GetFee(account, isGetFee); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyManager { _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, 'SPHYNX: Automated market maker pair is already set to that value'); automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function setUsdAmountToSwap(uint256 _usdAmount) public onlyManager { usdAmountToSwap = _usdAmount; emit SetUsdAmountToSwap(usdAmountToSwap); } function updateMarketingWallet(address newMarketingWallet) public onlyManager { require(newMarketingWallet != marketingWallet, 'SPHYNX: The marketing wallet is already this address'); excludeFromFees(newMarketingWallet, true); excludeFromFees(marketingWallet, false); emit MarketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = payable(newMarketingWallet); } function updateDevelopmentgWallet(address newDevelopmentWallet) public onlyManager { require(newDevelopmentWallet != developmentWallet, 'SPHYNX: The development wallet is already this address'); excludeFromFees(newDevelopmentWallet, true); excludeFromFees(developmentWallet, false); emit DevelopmentWalletUpdated(newDevelopmentWallet, developmentWallet); developmentWallet = payable(newDevelopmentWallet); } function updateLotteryAddress(address newLotteryAddress) public onlyManager { require(newLotteryAddress != lotteryAddress, 'SPHYNX: The lottery wallet is already this address'); excludeFromFees(newLotteryAddress, true); excludeFromFees(lotteryAddress, false); emit LotteryAddressUpdated(newLotteryAddress, lotteryAddress); lotteryAddress = newLotteryAddress; } function setBlockNumber() public onlyOwner { blockNumber = block.number; emit SetBlockNumber(blockNumber); } function updateMaxTxAmount(uint256 _amount) public onlyManager { maxTxAmount = _amount; emit UpdateMaxTxAmount(_amount); } function updateTokenClaim(bool _claim) public onlyManager { claimable = _claim; } function updateStopTrade(bool _value) external onlySigner { require(stopTrade != _value, 'already-set'); require(!stopTradeSign[msg.sender], 'already-sign'); stopTradeSign[msg.sender] = true; if ( stopTradeSign[signersArray[0]] && stopTradeSign[signersArray[1]] && stopTradeSign[signersArray[2]] ) { stopTrade = _value; stopTradeSign[signersArray[0]] = false; stopTradeSign[signersArray[1]] = false; stopTradeSign[signersArray[2]] = false; } } function updateSignerWallet(address _signer) external onlySigner { signers[msg.sender] = false; signers[_signer] = true; for(uint i = 0; i < 3; i++) { if(signersArray[i] == msg.sender) { signersArray[i] = _signer; } } } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), 'BEP20: transfer from the zero address'); require(to != address(0), 'BEP20: transfer to the zero address'); require(!stopTrade, 'trade-stopped'); require(amount <= maxTxAmount, 'max-tx-amount-overflow'); if (amount == 0) { super._transfer(from, to, 0); return; } if(SwapAndLiquifyEnabled) { uint256 contractTokenBalance = balanceOf(address(this)); uint256 nativeTokenAmount = _getTokenAmountFromNative(); bool canSwap = contractTokenBalance >= nativeTokenAmount; if (canSwap && !swapping && !automatedMarketMakerPairs[from]) { swapping = true; // Set number of tokens to sell to nativeTokenAmount contractTokenBalance = nativeTokenAmount; swapTokens(contractTokenBalance); swapping = false; } } // indicates if fee should be deducted from transfer bool takeFee = true; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { if (block.number - blockNumber <= 10) { uint256 afterBalance = balanceOf(to) + amount; require(afterBalance <= 250000 * (10**18), 'Owned amount exceeds the maxOwnedAmount'); } uint256 fees; if (_isGetFees[from] || _isGetFees[to]) { if (block.number - blockNumber <= 5) { fees = amount.mul(99).div(10**2); } else { fees = amount.mul(totalFees).div(10**2); if (sendToLottery) { uint256 lotteryAmount = amount.mul(lotteryFee).div(10**2); amount = amount.sub(lotteryAmount); super._transfer(from, lotteryAddress, lotteryAmount); } } amount = amount.sub(fees); super._transfer(from, address(this), fees); } } super._transfer(from, to, amount); } function swapTokens(uint256 tokenAmount) private { swapTokensForNative(tokenAmount); uint256 swappedNative = address(this).balance; uint256 marketingNative = swappedNative.mul(marketingFee).div(totalFees); uint256 developmentNative = swappedNative.sub(marketingNative); transferNativeToMarketingWallet(marketingNative); transferNativeToDevelopmentWallet(developmentNative); } // Swap tokens on PacakeSwap function swapTokensForNative(uint256 tokenAmount) private { // generate the sphynxswap pair path of token -> WETH address[] memory path = new address[](2); path[0] = address(this); path[1] = sphynxSwapRouter.WETH(); _approve(address(this), address(sphynxSwapRouter), tokenAmount); // make the swap sphynxSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of Native path, address(this), block.timestamp ); } function getNativeAmountFromUSD() public view returns (uint256 amount) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); amount = usdAmountToSwap.mul(10 ** 26).div(uint256(price)); } function _getTokenAmountFromNative() internal view returns (uint256) { uint256 tokenAmount; address[] memory path = new address[](2); path[0] = sphynxSwapRouter.WETH(); path[1] = address(this); uint256 nativeAmountToSwap = getNativeAmountFromUSD(); uint256[] memory amounts = sphynxSwapRouter.getAmountsOut(nativeAmountToSwap, path); tokenAmount = amounts[1]; return tokenAmount; } function transferNativeToMarketingWallet(uint256 amount) private { marketingWallet.transfer(amount); } function transferNativeToDevelopmentWallet(uint256 amount) private { developmentWallet.transfer(amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.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 {} 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; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import '../GSN/Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an manager) that can be granted exclusive access to * specific functions. * * By default, the manager account will be the one that deploys the contract. This * can later be changed with {transferManagement}. * * This module is used through inheritance. It will make available the modifier * `onlyManager`, which can be applied to your functions to restrict their use to * the manager. */ contract Manageable is Context { address private _manager; event ManagementTransferred(address indexed previousManager, address indexed newManager); /** * @dev Initializes the contract setting the deployer as the initial manager. */ constructor() internal { address msgSender = _msgSender(); _manager = msgSender; emit ManagementTransferred(address(0), msgSender); } /** * @dev Returns the address of the current manager. */ function manager() public view returns (address) { return _manager; } /** * @dev Throws if called by any account other than the manager. */ modifier onlyManager() { require(_manager == _msgSender(), 'Manageable: caller is not the manager'); _; } /** * @dev Leaves the contract without manager. It will not be possible to call * `onlyManager` functions anymore. Can only be called by the current manager. * * NOTE: Renouncing management will leave the contract without an manager, * thereby removing any functionality that is only available to the manager. */ function renounceManagement() public onlyManager { emit ManagementTransferred(_manager, address(0)); _manager = address(0); } /** * @dev Transfers management of the contract to a new account (`newManager`). * Can only be called by the current manager. */ function transferManagement(address newManager) public onlyManager { _transferManagement(newManager); } /** * @dev Transfers management of the contract to a new account (`newManager`). */ function _transferManagement(address newManager) internal { require(newManager != address(0), 'Manageable: new manager is the zero address'); emit ManagementTransferred(_manager, newManager); _manager = newManager; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; import '../../access/Ownable.sol'; import '../../GSN/Context.sol'; import './IBEP20.sol'; import '../../math/SafeMath.sol'; import '../../utils/Address.sol'; /** * @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}. */ contract BEP20 is Context, IBEP20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero') ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Destroys `amount` tokens from `msg.sender`, decreasing the total supply. * */ function burn(uint256 amount) public returns (bool) { _burn(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), '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); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance') ); } } pragma solidity >=0.5.0; interface ISphynxPair { 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 swapFee() external view returns (uint32); 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; function setSwapFee(uint32) external; } pragma solidity >=0.5.0; interface ISphynxFactory { 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; function setSwapFee(address _pair, uint32 _swapFee) external; } pragma solidity >=0.6.2; import './ISphynxRouter01.sol'; interface ISphynxRouter02 is ISphynxRouter01 { 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; } pragma solidity >=0.6.2; interface ISphynxRouter01 { 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, uint swapFee) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint swapFee) 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); }
Transfers management of the contract to a new account (`newManager`)./
function _transferManagement(address newManager) internal { require(newManager != address(0), 'Manageable: new manager is the zero address'); emit ManagementTransferred(_manager, newManager); _manager = newManager; }
1,357,292
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @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: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol pragma solidity ^0.4.24; /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: contracts/interfaces/IAMB.sol pragma solidity 0.4.24; interface IAMB { function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32); function requireToConfirmMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32); function sourceChainId() external view returns (uint256); function destinationChainId() external view returns (uint256); } // File: contracts/interfaces/ERC677.sol pragma solidity 0.4.24; contract ERC677 is ERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address, uint256, bytes) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) public returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); } contract LegacyERC20 { function transfer(address _spender, uint256 _value) public; // returns (bool); function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.4.24; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.4.24; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.4.24; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); /* solcov ignore next */ _; } /** * @dev Throws if called by any account other than contract itself or owner. */ modifier onlyRelevantSender() { // proxy owner if used through proxy, address(0) otherwise require( !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); /* solcov ignore next */ _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[OWNER]; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner the address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiTokenBridge.sol pragma solidity 0.4.24; contract BasicMultiTokenBridge is EternalStorage, Ownable { using SafeMath for uint256; // token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens event DailyLimitChanged(address indexed token, uint256 newLimit); event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit); /** * @dev Checks if specified token was already bridged at least once. * @param _token address of the token contract. * @return true, if token address is address(0) or token was already bridged. */ function isTokenRegistered(address _token) public view returns (bool) { return minPerTx(_token) > 0; } /** * @dev Retrieves the total spent amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens sent through the bridge to the other side. */ function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("tSpD", _token, _day))]; } /** * @dev Retrieves the total executed amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens received from the bridge from the other side. */ function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))]; } /** * @dev Retrieves current daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be sent through the bridge per day. */ function dailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))]; } /** * @dev Retrieves current execution daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be received from the bridge on the other side per day. */ function executionDailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))]; } /** * @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can be sent through the bridge in one transfer. */ function maxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))]; } /** * @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can received from the bridge on the other side in one transaction. */ function executionMaxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))]; } /** * @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return minimum amount on tokens that can be sent through the bridge in one transfer. */ function minPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))]; } /** * @dev Checks that bridged amount of tokens conforms to the configured limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be bridged. */ function withinLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount); return dailyLimit(address(0)) > 0 && dailyLimit(_token) >= nextLimit && _amount <= maxPerTx(_token) && _amount >= minPerTx(_token); } /** * @dev Checks that bridged amount of tokens conforms to the configured execution limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be processed and executed. */ function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount); return executionDailyLimit(address(0)) > 0 && executionDailyLimit(_token) >= nextLimit && _amount <= executionMaxPerTx(_token); } /** * @dev Returns current day number. * @return day number. */ function getCurrentDay() public view returns (uint256) { // solhint-disable-next-line not-rely-on-time return block.timestamp / 1 days; } /** * @dev Updates daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the efault limit. * @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit; emit DailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit; emit ExecutionDailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx; } /** * @dev Updates maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx; } /** * @dev Updates minumum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _minPerTx minumum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit. */ function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token)); uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @param _token address of the token contract, or address(0) for the default limit. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx(address _token) public view returns (uint256) { uint256 _maxPerTx = maxPerTx(_token); uint256 _dailyLimit = dailyLimit(_token); uint256 _spent = totalSpentPerDay(_token, getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } /** * @dev Internal function for adding spent amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalSpentPerDay(address _token, uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("tSpD", _token, _day))] = totalSpentPerDay(_token, _day).add(_value); } /** * @dev Internal function for adding execcuted amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalExecutedPerDay(address _token, uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay( _token, _day ) .add(_value); } /** * @dev Internal function for initializing limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]. */ function _setLimits(address _token, uint256[3] _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1]; uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2]; emit DailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing execution limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]. */ function _setExecutionLimits(address _token, uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1]; emit ExecutionDailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing limits for some token relative to its decimals parameter. * @param _token address of the token contract. * @param _decimals token decimals parameter. */ function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal { uint256 factor; if (_decimals < 18) { factor = 10**(18 - _decimals); uint256 _minPerTx = minPerTx(address(0)).div(factor); uint256 _maxPerTx = maxPerTx(address(0)).div(factor); uint256 _dailyLimit = dailyLimit(address(0)).div(factor); uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor); uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor); // such situation can happen when calculated limits relative to the token decimals are too low // e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed. // in this case, limits are raised to the default values if (_minPerTx == 0) { // Numbers 1, 100, 10000 are chosen in a semi-random way, // so that any token with small decimals can still be bridged in some amounts. // It is possible to override limits for the particular token later if needed. _minPerTx = 1; if (_maxPerTx <= _minPerTx) { _maxPerTx = 100; _executionMaxPerTx = 100; if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) { _dailyLimit = 10000; _executionDailyLimit = 10000; } } } _setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]); _setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]); } else { factor = 10**(_decimals - 18); _setLimits( _token, [dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)] ); _setExecutionLimits( _token, [executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)] ); } } } // File: contracts/libraries/Bytes.sol pragma solidity 0.4.24; /** * @title Bytes * @dev Helper methods to transform bytes to other solidity types. */ library Bytes { /** * @dev Converts bytes array to bytes32. * Truncates bytes array if its size is more than 32 bytes. * NOTE: This function does not perform any checks on the received parameter. * Make sure that the _bytes argument has a correct length, not less than 32 bytes. * A case when _bytes has length less than 32 will lead to the undefined behaviour, * since assembly will read data from memory that is not related to the _bytes argument. * @param _bytes to be converted to bytes32 type * @return bytes32 type of the firsts 32 bytes array in parameter. */ function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) { assembly { result := mload(add(_bytes, 32)) } } /** * @dev Truncate bytes array if its size is more than 20 bytes. * NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes. * @param _bytes to be converted to address type * @return address included in the firsts 20 bytes of the bytes array in parameter. */ function bytesToAddress(bytes _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } } } // File: openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.24; /** * 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; } } // File: contracts/upgradeable_contracts/BasicAMBMediator.sol pragma solidity 0.4.24; /** * @title BasicAMBMediator * @dev Basic storage and methods needed by mediators to interact with AMB bridge. */ contract BasicAMBMediator is Ownable { bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract")) bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract")) bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit")) /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator { require(msg.sender == address(bridgeContract())); require(messageSender() == mediatorContractOnOtherSide()); _; } /** * @dev Sets the AMB bridge contract address. Only the owner can call this method. * @param _bridgeContract the address of the bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { _setBridgeContract(_bridgeContract); } /** * @dev Sets the mediator contract address from the other network. Only the owner can call this method. * @param _mediatorContract the address of the mediator contract. */ function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner { _setMediatorContractOnOtherSide(_mediatorContract); } /** * @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network. * This value can't exceed the parameter maxGasPerTx defined on the AMB bridge. * Only the owner can call this method. * @param _requestGasLimit the gas limit for the message execution. */ function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner { _setRequestGasLimit(_requestGasLimit); } /** * @dev Get the AMB interface for the bridge contract address * @return AMB interface for the bridge contract address */ function bridgeContract() public view returns (IAMB) { return IAMB(addressStorage[BRIDGE_CONTRACT]); } /** * @dev Tells the mediator contract address from the other network. * @return the address of the mediator contract. */ function mediatorContractOnOtherSide() public view returns (address) { return addressStorage[MEDIATOR_CONTRACT]; } /** * @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network. * @return the gas limit for the message execution. */ function requestGasLimit() public view returns (uint256) { return uintStorage[REQUEST_GAS_LIMIT]; } /** * @dev Stores a valid AMB bridge contract address. * @param _bridgeContract the address of the bridge contract. */ function _setBridgeContract(address _bridgeContract) internal { require(AddressUtils.isContract(_bridgeContract)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } /** * @dev Stores the mediator contract address from the other network. * @param _mediatorContract the address of the mediator contract. */ function _setMediatorContractOnOtherSide(address _mediatorContract) internal { addressStorage[MEDIATOR_CONTRACT] = _mediatorContract; } /** * @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network. * @param _requestGasLimit the gas limit for the message execution. */ function _setRequestGasLimit(uint256 _requestGasLimit) internal { require(_requestGasLimit <= maxGasPerTx()); uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit; } /** * @dev Tells the address that generated the message on the other network that is currently being executed by * the AMB bridge. * @return the address of the message sender. */ function messageSender() internal view returns (address) { return bridgeContract().messageSender(); } /** * @dev Tells the id of the message originated on the other network. * @return the id of the message originated on the other network. */ function messageId() internal view returns (bytes32) { return bridgeContract().messageId(); } /** * @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network. * @return the maximum gas limit value. */ function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); } } // File: contracts/upgradeable_contracts/ChooseReceiverHelper.sol pragma solidity 0.4.24; contract ChooseReceiverHelper { /** * @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data. * @param _from address of tokens sender. * @param _data passed data in the transfer message. * @return address of the receiver on the other side. */ function chooseReceiver(address _from, bytes _data) internal view returns (address recipient) { recipient = _from; if (_data.length > 0) { require(_data.length == 20); recipient = Bytes.bytesToAddress(_data); require(recipient != address(0)); require(recipient != bridgeContractOnOtherSide()); } } /* solcov ignore next */ function bridgeContractOnOtherSide() internal view returns (address); } // File: contracts/upgradeable_contracts/TransferInfoStorage.sol pragma solidity 0.4.24; contract TransferInfoStorage is EternalStorage { /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } /** * @dev Sets that the message sent to the AMB bridge has been fixed. * @param _messageId of the message sent to the bridge. */ function setMessageFixed(bytes32 _messageId) internal { boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true; } /** * @dev Tells if a message sent to the AMB bridge has been fixed. * @return bool indicating the status of the message. */ function messageFixed(bytes32 _messageId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))]; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenBridgeMediator.sol pragma solidity 0.4.24; /** * @title MultiTokenBridgeMediator * @dev Common mediator functionality to handle operations related to multi-token bridge messages sent to AMB bridge. */ contract MultiTokenBridgeMediator is BasicAMBMediator, BasicMultiTokenBridge, TransferInfoStorage, ChooseReceiverHelper { event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value); event TokensBridgingInitiated( address indexed token, address indexed sender, uint256 value, bytes32 indexed messageId ); event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId); /** * @dev Stores the bridged token of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _token bridged token address. */ function setMessageToken(bytes32 _messageId, address _token) internal { addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token; } /** * @dev Tells the bridged token address of a message sent to the AMB bridge. * @return address of a token contract. */ function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20/ERC677 token * @param _recipient address that will receive the tokens * @param _value amount of tokens to be received */ function _handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) internal { if (withinExecutionLimit(_token, _value)) { addTotalExecutedPerDay(_token, getCurrentDay(), _value); executeActionOnBridgedTokens(_token, _recipient, _value); } else { executeActionOnBridgedTokensOutOfLimit(_token, _recipient, _value); } } /** * @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to * fix/roll back the transferred assets on the other network. * @param _messageId id of the message which execution failed. */ function requestFailedMessageFix(bytes32 _messageId) external { require(!bridgeContract().messageCallStatus(_messageId)); require(bridgeContract().failedMessageReceiver(_messageId) == address(this)); require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide()); bytes4 methodSelector = this.fixFailedMessage.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _messageId); bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit()); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) public onlyMediator { require(!messageFixed(_messageId)); address token = messageToken(_messageId); address recipient = messageRecipient(_messageId); uint256 value = messageValue(_messageId); setMessageFixed(_messageId); executeActionOnFixedTokens(token, recipient, value); emit FailedMessageFixed(_messageId, token, recipient, value); } /** * @dev Execute the action to be performed when the bridge tokens are out of execution limits. */ function executeActionOnBridgedTokensOutOfLimit(address, address, uint256) internal { revert(); } /* solcov ignore next */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal; /* solcov ignore next */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal; } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.4.24; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/upgradeable_contracts/ReentrancyGuard.sol pragma solidity 0.4.24; contract ReentrancyGuard is EternalStorage { bytes32 internal constant LOCK = 0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92; // keccak256(abi.encodePacked("lock")) function lock() internal returns (bool) { return boolStorage[LOCK]; } function setLock(bool _lock) internal { boolStorage[LOCK] = _lock; } } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.4.24; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner()); /* solcov ignore next */ _; } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.4.24; contract Sacrifice { constructor(address _recipient) public payable { selfdestruct(_recipient); } } // File: contracts/libraries/Address.sol pragma solidity 0.4.24; /** * @title Address * @dev Helper methods for Address type. */ library Address { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address _receiver, uint256 _value) internal { if (!_receiver.send(_value)) { (new Sacrifice).value(_value)(_receiver); } } } // File: contracts/libraries/SafeERC20.sol pragma solidity 0.4.24; /** * @title SafeERC20 * @dev Helper methods for safe token transfers. * Functions perform additional checks to be sure that token transfer really happened. */ library SafeERC20 { using SafeMath for uint256; /** * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _to address of the receiver * @param _value amount of tokens to send */ function safeTransfer(address _token, address _to, uint256 _value) internal { LegacyERC20(_token).transfer(_to, _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } /** * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _from address of the sender * @param _value amount of tokens to send */ function safeTransferFrom(address _token, address _from, uint256 _value) internal { LegacyERC20(_token).transferFrom(_from, address(this), _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.4.24; /** * @title Claimable * @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations. */ contract Claimable { using SafeERC20 for address; /** * Throws if a given address is equal to address(0) */ modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimValues(address _token, address _to) internal validAddress(_to) { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; Address.safeSendValue(_to, value); } /** * @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function claimErc20Tokens(address _token, address _to) internal { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); _token.safeTransfer(_to, balance); } } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.4.24; contract VersionableBridge { function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (5, 2, 0); } /* solcov ignore next */ function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title BasicMultiAMBErc20ToErc677 * @dev Common functionality for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. */ contract BasicMultiAMBErc20ToErc677 is Initializable, ReentrancyGuard, Upgradeable, Claimable, VersionableBridge, MultiTokenBridgeMediator { /** * @dev Tells the address of the mediator contract on the other side, used by chooseReceiver method * to avoid sending the native tokens to that address. * @return address of the mediator contract con the other side */ function bridgeContractOnOtherSide() internal view returns (address) { return mediatorContractOnOtherSide(); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(ERC677 token, address _receiver, uint256 _value) external { _relayTokens(token, _receiver, _value); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(ERC677 token, uint256 _value) external { _relayTokens(token, msg.sender, _value); } /** * @dev Tells the bridge interface version that this contract supports. * @return major value of the version * @return minor value of the version * @return patch value of the version */ function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (1, 2, 0); } /** * @dev Tells the bridge mode that this contract supports. * @return _data 4 bytes representing the bridge mode */ function getBridgeMode() external pure returns (bytes4 _data) { return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb"))) } /** * @dev Claims stucked tokens. Only unsupported tokens can be claimed. * When dealing with already supported tokens, fixMediatorBalance can be used instead. * @param _token address of claimed token, address(0) for native * @param _to address of tokens receiver */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Only unregistered tokens and native coins are allowed to be claimed with the use of this function require(_token == address(0) || !isTokenRegistered(_token)); claimValues(_token, _to); } /* solcov ignore next */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool); /* solcov ignore next */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal; /* solcov ignore next */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal; } // File: contracts/upgradeability/Proxy.sol pragma solidity 0.4.24; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ /* solcov ignore next */ function implementation() public view returns (address); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function() public payable { // solhint-disable-previous-line no-complex-fallback address _impl = implementation(); require(_impl != address(0)); assembly { /* 0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40) loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty memory. It's needed because we're going to write the return data of delegatecall to the free memory slot. */ let ptr := mload(0x40) /* `calldatacopy` is copy calldatasize bytes from calldata First argument is the destination to which data is copied(ptr) Second argument specifies the start position of the copied data. Since calldata is sort of its own unique location in memory, 0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata. That's always going to be the zeroth byte of the function selector. Third argument, calldatasize, specifies how much data will be copied. calldata is naturally calldatasize bytes long (same thing as msg.data.length) */ calldatacopy(ptr, 0, calldatasize) /* delegatecall params explained: gas: the amount of gas to provide for the call. `gas` is an Opcode that gives us the amount of gas still available to execution _impl: address of the contract to delegate to ptr: to pass copied data calldatasize: loads the size of `bytes memory data`, same as msg.data.length 0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic, these are set to 0, 0 so the output data will not be written to memory. The output data will be read using `returndatasize` and `returdatacopy` instead. result: This will be 0 if the call fails and 1 if it succeeds */ let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) /* */ /* ptr current points to the value stored at 0x40, because we assigned it like ptr := mload(0x40). Because we use 0x40 as a free memory pointer, we want to make sure that the next time we want to allocate memory, we aren't overwriting anything important. So, by adding ptr and returndatasize, we get a memory location beyond the end of the data we will be copying to ptr. We place this in at 0x40, and any reads from 0x40 will now read from free memory */ mstore(0x40, add(ptr, returndatasize)) /* `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the slot it will copy to, 0 means copy from the beginning of the return data, and size is the amount of data to copy. `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall */ returndatacopy(ptr, 0, returndatasize) /* if `result` is 0, revert. if `result` is 1, return `size` amount of data from `ptr`. This is the data that was copied to `ptr` from the delegatecall return data */ switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } } // File: contracts/interfaces/IBridgeMediator.sol interface IBridgeMediator { function tokenImage() public view returns (address); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/TokenProxy.sol pragma solidity 0.4.24; interface IPermittableTokenVersion { function version() external pure returns (string); } /** * @title TokenProxy * @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract. */ contract TokenProxy is Proxy { // storage layout is copied from PermittableToken.sol string internal name; string internal symbol; uint8 internal decimals; mapping(address => uint256) internal balances; uint256 internal totalSupply; mapping(address => mapping(address => uint256)) internal allowed; address internal owner; bool internal mintingFinished; address internal bridgeContractAddr; // string public constant version = "1"; bytes32 internal DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; mapping(address => uint256) internal nonces; mapping(address => mapping(address => uint256)) internal expirations; /** * @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage. * @param _tokenImage address of the token image used for mirroring all functions. * @param _name token name. * @param _symbol token symbol. * @param _decimals token decimals. * @param _chainId chain id for current network. */ constructor(address _tokenImage, string memory _name, string memory _symbol, uint8 _decimals, uint256 _chainId) public { string memory version = IPermittableTokenVersion(_tokenImage).version(); name = _name; symbol = _symbol; decimals = _decimals; owner = msg.sender; // msg.sender == HomeMultiAMBErc20ToErc677 mediator bridgeContractAddr = msg.sender; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(_name)), keccak256(bytes(version)), _chainId, address(this) ) ); } /** * @dev Retrieves the implementation contract address, mirrored token image. * @return token image address. */ function implementation() public view returns (address impl) { return IBridgeMediator(bridgeContractAddr).tokenImage(); } } // File: contracts/upgradeable_contracts/BaseRewardAddressList.sol pragma solidity 0.4.24; /** * @title BaseRewardAddressList * @dev Implements the logic to store, add and remove reward account addresses. Works as a linked list. */ contract BaseRewardAddressList is EternalStorage { using SafeMath for uint256; address public constant F_ADDR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; uint256 internal constant MAX_REWARD_ADDRESSES = 50; bytes32 internal constant REWARD_ADDRESS_COUNT = 0xabc77c82721ced73eef2645facebe8c30249e6ac372cce6eb9d1fed31bd6648f; // keccak256(abi.encodePacked("rewardAddressCount")) event RewardAddressAdded(address indexed addr); event RewardAddressRemoved(address indexed addr); /** * @dev Retrieves all registered reward accounts. * @return address list of the registered reward receivers. */ function rewardAddressList() external view returns (address[]) { address[] memory list = new address[](rewardAddressCount()); uint256 counter = 0; address nextAddr = getNextRewardAddress(F_ADDR); while (nextAddr != F_ADDR) { require(nextAddr != address(0)); list[counter] = nextAddr; nextAddr = getNextRewardAddress(nextAddr); counter++; } return list; } /** * @dev Retrieves amount of registered reward accounts. * @return length of reward addresses list. */ function rewardAddressCount() public view returns (uint256) { return uintStorage[REWARD_ADDRESS_COUNT]; } /** * @dev Checks if specified address is included into the registered rewards receivers list. * @param _addr address to verify. * @return true, if specified address is associated with one of the registered reward accounts. */ function isRewardAddress(address _addr) public view returns (bool) { return _addr != F_ADDR && getNextRewardAddress(_addr) != address(0); } /** * @dev Retrieves next reward address in the linked list, or F_ADDR if given address is the last one. * @param _address address of some reward account. * @return address of the next reward receiver. */ function getNextRewardAddress(address _address) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("rewardAddressList", _address))]; } /** * @dev Internal function for adding a new reward address to the linked list. * @param _addr new reward account. */ function _addRewardAddress(address _addr) internal { require(_addr != address(0) && _addr != F_ADDR); require(!isRewardAddress(_addr)); address nextAddr = getNextRewardAddress(F_ADDR); require(nextAddr != address(0)); _setNextRewardAddress(_addr, nextAddr); _setNextRewardAddress(F_ADDR, _addr); _setRewardAddressCount(rewardAddressCount().add(1)); } /** * @dev Internal function for removing existing reward address from the linked list. * @param _addr old reward account which should be removed. */ function _removeRewardAddress(address _addr) internal { require(isRewardAddress(_addr)); address nextAddr = getNextRewardAddress(_addr); address index = F_ADDR; address next = getNextRewardAddress(index); while (next != _addr) { require(next != address(0)); index = next; next = getNextRewardAddress(index); require(next != F_ADDR); } _setNextRewardAddress(index, nextAddr); delete addressStorage[keccak256(abi.encodePacked("rewardAddressList", _addr))]; _setRewardAddressCount(rewardAddressCount().sub(1)); } /** * @dev Internal function for initializing linked list with the array of the initial reward addresses. * @param _rewardAddresses initial reward addresses list, should be non-empty. */ function _setRewardAddressList(address[] _rewardAddresses) internal { require(_rewardAddresses.length > 0); _setNextRewardAddress(F_ADDR, _rewardAddresses[0]); for (uint256 i = 0; i < _rewardAddresses.length; i++) { require(_rewardAddresses[i] != address(0) && _rewardAddresses[i] != F_ADDR); require(!isRewardAddress(_rewardAddresses[i])); if (i == _rewardAddresses.length - 1) { _setNextRewardAddress(_rewardAddresses[i], F_ADDR); } else { _setNextRewardAddress(_rewardAddresses[i], _rewardAddresses[i + 1]); } emit RewardAddressAdded(_rewardAddresses[i]); } _setRewardAddressCount(_rewardAddresses.length); } /** * @dev Internal function for updating the length of the reward accounts list. * @param _rewardAddressCount new linked list length. */ function _setRewardAddressCount(uint256 _rewardAddressCount) internal { require(_rewardAddressCount <= MAX_REWARD_ADDRESSES); uintStorage[REWARD_ADDRESS_COUNT] = _rewardAddressCount; } /** * @dev Internal function for updating the pointer to the next reward receiver. * @param _prevAddr address of some reward receiver. * @param _addr address of the next receiver to which _prevAddr should point to. */ function _setNextRewardAddress(address _prevAddr, address _addr) internal { addressStorage[keccak256(abi.encodePacked("rewardAddressList", _prevAddr))] = _addr; } } // File: contracts/interfaces/IBurnableMintableERC677Token.sol pragma solidity 0.4.24; contract IBurnableMintableERC677Token is ERC677 { function mint(address _to, uint256 _amount) public returns (bool); function burn(uint256 _value) public; function claimTokens(address _token, address _to) external; } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeFeeManagerMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title HomeFeeManagerMultiAMBErc20ToErc677 * @dev Implements the logic to distribute fees from the multi erc20 to erc677 mediator contract operations. * The fees are distributed in the form of native tokens to the list of reward accounts. */ contract HomeFeeManagerMultiAMBErc20ToErc677 is BaseRewardAddressList, Ownable, BasicMultiTokenBridge { using SafeMath for uint256; event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee); event FeeDistributed(uint256 fee, address indexed token, bytes32 indexed messageId); // This is not a real fee value but a relative value used to calculate the fee percentage uint256 internal constant MAX_FEE = 1 ether; bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee")) bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee")) /** * @dev Throws if given fee percentage is >= 100%. */ modifier validFee(uint256 _fee) { require(_fee < MAX_FEE); /* solcov ignore next */ _; } /** * @dev Throws if given fee type is unknown. */ modifier validFeeType(bytes32 _feeType) { require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE); /* solcov ignore next */ _; } /** * @dev Adds a new reward address to the list, which will receive fees collected from the bridge operations. * Only the owner can call this method. * @param _addr new reward account. */ function addRewardAddress(address _addr) external onlyOwner { _addRewardAddress(_addr); } /** * @dev Removes a reward address from the rewards list. * Only the owner can call this method. * @param _addr old reward account, that should be removed. */ function removeRewardAddress(address _addr) external onlyOwner { _removeRewardAddress(_addr); } /** * @dev Updates the value for the particular fee type. * Only the owner can call this method. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function setFee(bytes32 _feeType, address _token, uint256 _fee) external onlyOwner { _setFee(_feeType, _token, _fee); } /** * @dev Retrieves the value for the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @return fee value associated with the requested fee type. */ function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) { return uintStorage[keccak256(abi.encodePacked(_feeType, _token))]; } /** * @dev Calculates the amount of fee to pay for the value of the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return amount of fee to be subtracted from the transferred value. */ function calculateFee(bytes32 _feeType, address _token, uint256 _value) public view returns (uint256) { uint256 _fee = getFee(_feeType, _token); return _value.mul(_fee).div(MAX_FEE); } /** * @dev Internal function for updating the fee value for the given fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function _setFee(bytes32 _feeType, address _token, uint256 _fee) internal validFeeType(_feeType) validFee(_fee) { require(isTokenRegistered(_token)); uintStorage[keccak256(abi.encodePacked(_feeType, _token))] = _fee; emit FeeUpdated(_feeType, _token, _fee); } /** * @dev Calculates a random number based on the block number. * @param _count the max value for the random number. * @return a number between 0 and _count. */ function random(uint256 _count) internal view returns (uint256) { return uint256(blockhash(block.number.sub(1))) % _count; } /** * @dev Calculates and distributes the amount of fee proportionally between registered reward addresses. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return total amount of fee subtracted from the transferred value and distributed between the reward accounts. */ function _distributeFee(bytes32 _feeType, address _token, uint256 _value) internal returns (uint256) { uint256 numOfAccounts = rewardAddressCount(); uint256 _fee = calculateFee(_feeType, _token, _value); if (numOfAccounts == 0 || _fee == 0) { return 0; } uint256 feePerAccount = _fee.div(numOfAccounts); uint256 randomAccountIndex; uint256 diff = _fee.sub(feePerAccount.mul(numOfAccounts)); if (diff > 0) { randomAccountIndex = random(numOfAccounts); } address nextAddr = getNextRewardAddress(F_ADDR); require(nextAddr != F_ADDR && nextAddr != address(0)); uint256 i = 0; while (nextAddr != F_ADDR) { uint256 feeToDistribute = feePerAccount; if (diff > 0 && randomAccountIndex == i) { feeToDistribute = feeToDistribute.add(diff); } if (_feeType == HOME_TO_FOREIGN_FEE) { ERC677(_token).transfer(nextAddr, feeToDistribute); } else { IBurnableMintableERC677Token(_token).mint(nextAddr, feeToDistribute); } nextAddr = getNextRewardAddress(nextAddr); require(nextAddr != address(0)); i = i + 1; } return _fee; } } // File: contracts/interfaces/IBridgeUtils.sol pragma solidity 0.4.24; interface IBridgeUtils { function addToken(address _tokenAddr) external returns (bool); function registerSupplier(address ownerAddr) external returns (address); function isRegistered(address supplierAddr) public view returns (bool); function safeForSupplier(address supplierAddr) public view returns (address); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenForwardingRules.sol pragma solidity 0.4.24; /** * @title MultiTokenForwardingRules * @dev Multi token mediator functionality for managing destination AMB lanes permissions. */ contract MultiTokenForwardingRules is Ownable { address internal constant ANY_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; event ForwardingRuleUpdated(address token, address sender, address receiver, int256 lane); /** * @dev Tells the destination lane for a particular bridge operation by checking several wildcard forwarding rules. * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @return destination lane identifier, where the message should be forwarded to. * 1 - oracle-driven-lane should be used. * 0 - default behaviour should be applied. * -1 - manual lane should be used. */ function destinationLane(address _token, address _sender, address _receiver) public view returns (int256) { int256 defaultLane = forwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS); // specific token for all senders and receivers int256 lane; if (defaultLane < 0) { lane = forwardingRule(_token, _sender, ANY_ADDRESS); // specific token for specific sender if (lane != 0) return lane; lane = forwardingRule(_token, ANY_ADDRESS, _receiver); // specific token for specific receiver if (lane != 0) return lane; return defaultLane; } lane = forwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS); // all tokens for specific sender if (lane != 0) return lane; return forwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver); // all tokens for specific receiver } /** * Updates the forwarding rule for bridging specific token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _enable true, if bridge operations for a given token should be forwarded to the manual lane. */ function setTokenForwardingRule(address _token, bool _enable) external { require(_token != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS, _enable ? int256(-1) : int256(0)); } /** * Allows a particular address to send bridge requests to the oracle-driven lane for a particular token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _sender address of the tokens sender on the home side of the bridge. * @param _enable true, if bridge operations for a given token and sender should be forwarded to the oracle-driven lane. */ function setSenderExceptionForTokenForwardingRule(address _token, address _sender, bool _enable) external { require(_token != ANY_ADDRESS); require(_sender != ANY_ADDRESS); _setForwardingRule(_token, _sender, ANY_ADDRESS, _enable ? int256(1) : int256(0)); } /** * Allows a particular address to receive bridged tokens from the oracle-driven lane for a particular token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @param _enable true, if bridge operations for a given token and receiver should be forwarded to the oracle-driven lane. */ function setReceiverExceptionForTokenForwardingRule(address _token, address _receiver, bool _enable) external { require(_token != ANY_ADDRESS); require(_receiver != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, _receiver, _enable ? int256(1) : int256(0)); } /** * Updates the forwarding rule for the specific sender. * Only owner can call this method. * @param _sender address of the tokens sender on the home side. * @param _enable true, if all bridge operations from a given sender should be forwarded to the manual lane. */ function setSenderForwardingRule(address _sender, bool _enable) external { require(_sender != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS, _enable ? int256(-1) : int256(0)); } /** * Updates the forwarding rule for the specific receiver. * Only owner can call this method. * @param _receiver address of the tokens receiver on the foreign side. * @param _enable true, if all bridge operations to a given receiver should be forwarded to the manual lane. */ function setReceiverForwardingRule(address _receiver, bool _enable) external { require(_receiver != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver, _enable ? int256(-1) : int256(0)); } /** * @dev Tells forwarding rule set up for a particular bridge operation. * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @return preferred destination lane for the particular bridge operation. */ function forwardingRule(address _token, address _sender, address _receiver) public view returns (int256) { return intStorage[keccak256(abi.encodePacked("f2", _token, _sender, _receiver))]; } /** * @dev Internal function for updating the preferred destination lane for the specific wildcard pattern. * Only owner can call this method. * Examples: * _setForwardingRule(tokenA, ANY_ADDRESS, ANY_ADDRESS, -1) - forward all operations on tokenA to the manual lane * _setForwardingRule(tokenA, Alice, ANY_ADDRESS, 1) - allow Alice to use the oracle-driven lane for bridging tokenA * _setForwardingRule(tokenA, ANY_ADDRESS, Bob, 1) - forward all tokenA bridge operations, where Bob is the receiver, to the oracle-driven lane * _setForwardingRule(ANY_ADDRESS, Mallory, ANY_ADDRESS, -1) - forward all bridge operations from Mallory to the manual lane * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @param _lane preferred destination lane for the particular sender. * 1 - forward to the oracle-driven lane. * 0 - behaviour is unset, proceed by checking other less-specific rules. * -1 - manual lane should be used. */ function _setForwardingRule(address _token, address _sender, address _receiver, int256 _lane) internal onlyOwner { intStorage[keccak256(abi.encodePacked("f2", _token, _sender, _receiver))] = _lane; emit ForwardingRuleUpdated(_token, _sender, _receiver, _lane); } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title HomeMultiAMBErc20ToErc677 * @dev Home side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract HomeMultiAMBErc20ToErc677 is BasicMultiAMBErc20ToErc677, HomeFeeManagerMultiAMBErc20ToErc677, MultiTokenForwardingRules { bytes32 internal constant TOKEN_IMAGE_CONTRACT = 0x20b8ca26cc94f39fab299954184cf3a9bd04f69543e4f454fab299f015b8130f; // keccak256(abi.encodePacked("tokenImageContract")) bytes32 internal constant BRIDGE_UTILS_CONTRACT = 0x174a58966ad4181674ba19a3131ba82f8683cbe56350f1172634244845855e9b; // keccak256(abi.encodePacked("bridgeUtilsContract")) event NewTokenRegistered(address indexed foreignToken, address indexed homeToken); event TokensBridgedToSafe( address indexed token, address indexed recipient, address safe, uint256 value, bytes32 indexed messageId ); /** * @dev Stores the initial parameters of the mediator. * @param _bridgeContract the address of the AMB bridge contract. * @param _mediatorContract the address of the mediator contract on the other network. * @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network. * [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ] * @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network. * [ 0 = executionDailyLimit, 1 = executionMaxPerTx ] * @param _requestGasLimit the gas limit for the message execution. * @param _owner address of the owner of the mediator contract. * @param _tokenImage address of the PermittableToken contract that will be used for deploying of new tokens. * @param _rewardAddresses list of reward addresses, between whom fees will be distributed. * @param _fees array with initial fees for both bridge directions. * [ 0 = homeToForeignFee, 1 = foreignToHomeFee ] */ function initialize( address _bridgeContract, address _mediatorContract, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ] uint256 _requestGasLimit, address _owner, address _tokenImage, address[] _rewardAddresses, uint256[2] _fees, // [ 0 = homeToForeignFee, 1 = foreignToHomeFee ], address _bridgeUtilsContract ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setBridgeUtilsContract(_bridgeUtilsContract); _setMediatorContractOnOtherSide(_mediatorContract); _setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); _setTokenImage(_tokenImage); if (_rewardAddresses.length > 0) { _setRewardAddressList(_rewardAddresses); } _setFee(HOME_TO_FOREIGN_FEE, address(0), _fees[0]); _setFee(FOREIGN_TO_HOME_FEE, address(0), _fees[1]); setInitialize(); return isInitialized(); } /** * @dev Updates an address of the token image contract used for proxifying newly created tokens. * @param _tokenImage address of PermittableToken contract. */ function setTokenImage(address _tokenImage) external onlyOwner { _setTokenImage(_tokenImage); } function setBridgeUtilsContract(address _bridgeUtilsContract) external onlyOwner { _setBridgeUtilsContract(_bridgeUtilsContract); } function _setBridgeUtilsContract(address _bridgeUtilsContract) internal { require(AddressUtils.isContract(_bridgeUtilsContract)); addressStorage[BRIDGE_UTILS_CONTRACT] = _bridgeUtilsContract; } /** * @dev Retrieves address of the token image contract. * @return address of block reward contract. */ function tokenImage() public view returns (address) { return addressStorage[TOKEN_IMAGE_CONTRACT]; } function bridgeUtils() public view returns (address) { return addressStorage[BRIDGE_UTILS_CONTRACT]; } /** * @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract. * Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token address of the bridged ERC20/ERC677 token on the foreign side. * @param _name name of the bridged token, "x" will be appended, if empty, symbol will be used instead. * @param _symbol symbol of the bridged token, "x" will be appended, if empty, name will be used instead. * @param _decimals decimals of the bridge foreign token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function deployAndHandleBridgedTokens( address _token, string _name, string _symbol, uint8 _decimals, address _recipient, uint256 _value ) external onlyMediator { string memory name = _name; string memory symbol = _symbol; require(bytes(name).length > 0 || bytes(symbol).length > 0); if (bytes(name).length == 0) { name = symbol; } else if (bytes(symbol).length == 0) { symbol = name; } name = string(abi.encodePacked(name, ".CPXD")); address homeToken = new TokenProxy(tokenImage(), name, symbol, _decimals, bridgeContract().sourceChainId()); _setTokenAddressPair(_token, homeToken); _initializeTokenBridgeLimits(homeToken, _decimals); _setFee(HOME_TO_FOREIGN_FEE, homeToken, getFee(HOME_TO_FOREIGN_FEE, address(0))); _setFee(FOREIGN_TO_HOME_FEE, homeToken, getFee(FOREIGN_TO_HOME_FEE, address(0))); IBridgeUtils bridgeUtilsInstance = IBridgeUtils(bridgeUtils()); bridgeUtilsInstance.addToken(homeToken); _handleBridgedTokens(ERC677(homeToken), _recipient, _value); emit NewTokenRegistered(_token, homeToken); } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20 token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator { ERC677 homeToken = ERC677(homeTokenAddress(_token)); require(isTokenRegistered(homeToken)); _handleBridgedTokens(homeToken, _recipient, _value); } /** * @dev ERC677 transfer callback function. * @param _from address of tokens sender. * @param _value amount of transferred tokens. * @param _data additional transfer data, can be used for passing alternative receiver address. */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) { // if onTokenTransfer is called as a part of call to _relayTokens, this callback does nothing if (!lock()) { ERC677 token = ERC677(msg.sender); // if msg.sender if not a valid token contract, this check will fail, since limits are zeros // so the following check is not needed // require(isTokenRegistered(token)); require(withinLimit(token, _value)); addTotalSpentPerDay(token, getCurrentDay(), _value); bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data); } return true; } /** * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract * and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network. * The user should first call Approve method of the ERC677 token. * @param token bridge token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal { // This lock is to prevent calling passMessage twice if a ERC677 token is used. // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract // which will call passMessage. require(!lock()); address to = address(this); // if msg.sender if not a valid token contract, this check will fail, since limits are zeros // so the following check is not needed // require(isTokenRegistered(token)); require(withinLimit(token, _value)); addTotalSpentPerDay(token, getCurrentDay(), _value); setLock(true); token.transferFrom(msg.sender, to, _value); setLock(false); bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver)); } /** * @dev Executes action on the request to deposit tokens relayed from the other network * @param _recipient address of tokens receiver * @param _value amount of bridged tokens */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal { bytes32 _messageId = messageId(); uint256 valueToMint = _value; uint256 fee = _distributeFee(FOREIGN_TO_HOME_FEE, _token, valueToMint); if (fee > 0) { emit FeeDistributed(fee, _token, _messageId); valueToMint = valueToMint.sub(fee); } address safeAddress; IBridgeUtils bridgeUtilsInstance = IBridgeUtils(bridgeUtils()); if (bridgeUtilsInstance.isRegistered(_recipient)) { safeAddress = bridgeUtilsInstance.safeForSupplier(_recipient); require(safeAddress != address(0)); } else { safeAddress = bridgeUtilsInstance.registerSupplier(_recipient); } IBurnableMintableERC677Token(_token).mint(safeAddress, valueToMint); emit TokensBridgedToSafe(_token, _recipient, safeAddress, valueToMint, _messageId); } /** * @dev Mints back the amount of tokens that were bridged to the other network but failed. * @param _token address that bridged token contract. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal { IBurnableMintableERC677Token(_token).mint(_recipient, _value); } /** * @dev Retrieves address of the home bridged token contract associated with a specific foreign token contract. * @param _foreignToken address of the created home token contract. * @return address of the home token contract. */ function homeTokenAddress(address _foreignToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("hta", _foreignToken))]; } /** * @dev Retrieves address of the foreign bridged token contract associated with a specific home token contract. * @param _homeToken address of the created home token contract. * @return address of the foreign token contract. */ function foreignTokenAddress(address _homeToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("fta", _homeToken))]; } /** * @dev Internal function for updating an address of the token image contract. * @param _foreignToken address of bridged foreign token contract. * @param _foreignToken address of created home token contract. */ function _setTokenAddressPair(address _foreignToken, address _homeToken) internal { addressStorage[keccak256(abi.encodePacked("hta", _foreignToken))] = _homeToken; addressStorage[keccak256(abi.encodePacked("fta", _homeToken))] = _foreignToken; } /** * @dev Internal function for updating an address of the token image contract. * @param _tokenImage address of deployed PermittableToken contract. */ function _setTokenImage(address _tokenImage) internal { require(AddressUtils.isContract(_tokenImage)); addressStorage[TOKEN_IMAGE_CONTRACT] = _tokenImage; } /** * @dev Executes action on withdrawal of bridged tokens * @param _token address of token contract * @param _from address of tokens sender * @param _value requested amount of bridged tokens * @param _data alternative receiver, if specified */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal { if (!lock()) { uint256 valueToBridge = _value; uint256 fee = 0; // Next line disables fee collection in case sender is one of the reward addresses. // It is needed to allow a 100% withdrawal of tokens from the home side. // If fees are not disabled for reward receivers, small fraction of tokens will always // be redistributed between the same set of reward addresses, which is not the desired behaviour. if (!isRewardAddress(_from)) { fee = _distributeFee(HOME_TO_FOREIGN_FEE, _token, valueToBridge); valueToBridge = valueToBridge.sub(fee); } IBurnableMintableERC677Token(_token).burn(valueToBridge); bytes32 _messageId = passMessage(_token, _from, chooseReceiver(_from, _data), valueToBridge); if (fee > 0) { emit FeeDistributed(fee, _token, _messageId); } } } /** * @dev Call AMB bridge to require the invocation of handleBridgedTokens method of the mediator on the other network. * Store information related to the bridged tokens in case the message execution fails on the other network * and the action needs to be fixed/rolled back. * @param _token bridged ERC20 token * @param _from address of sender, if bridge operation fails, tokens will be returned to this address * @param _receiver address of receiver on the other side, will eventually receive bridged tokens * @param _value bridged amount of tokens * @return id of the created and passed message */ function passMessage(ERC677 _token, address _from, address _receiver, uint256 _value) internal returns (bytes32) { bytes4 methodSelector = this.handleBridgedTokens.selector; address foreignToken = foreignTokenAddress(_token); bytes memory data = abi.encodeWithSelector(methodSelector, foreignToken, _receiver, _value); address executor = mediatorContractOnOtherSide(); uint256 gasLimit = requestGasLimit(); IAMB bridge = bridgeContract(); // Address of the foreign token is used here for determining lane permissions. // Such decision makes it possible to set rules for tokens that are not bridged yet. bytes32 _messageId = destinationLane(foreignToken, _from, _receiver) >= 0 ? bridge.requireToPassMessage(executor, data, gasLimit) : bridge.requireToConfirmMessage(executor, data, gasLimit); setMessageToken(_messageId, _token); setMessageValue(_messageId, _value); setMessageRecipient(_messageId, _from); emit TokensBridgingInitiated(_token, _from, _value, _messageId); return _messageId; } } // File: contracts/libraries/TokenReader.sol pragma solidity 0.4.24; /** * @title TokenReader * @dev Helper methods for reading name/symbol/decimals parameters from ERC20 token contracts. */ library TokenReader { bytes4 private constant _NAME = 0x06fdde03; // web3.eth.abi.encodeFunctionSignature("name()") bytes4 private constant _NAME_CAPS = 0xa3f4df7e; // web3.eth.abi.encodeFunctionSignature("NAME()") bytes4 private constant _SYMBOL = 0x95d89b41; // web3.eth.abi.encodeFunctionSignature("symbol") bytes4 private constant _SYMBOL_CAPS = 0xf76f8d78; // web3.eth.abi.encodeFunctionSignature("SYMBOL()") bytes4 private constant _DECIMALS = 0x313ce567; // web3.eth.abi.encodeFunctionSignature("decimals()") bytes4 private constant _DECIMALS_CAPS = 0x2e0f2625; // web3.eth.abi.encodeFunctionSignature("DECIMALS()") bytes4 private constant _TOTAL_SUPPLY = 0x18160ddd; // web3.eth.abi.encodeFunctionSignature("totalSupply()") bytes4 private constant _TOKEN_URI = 0xc87b56dd; // web3.eth.abi.encodeFunctionSignature("tokenURI(uint256)") /** * @dev Reads the name property of the provided token. * Either name() or NAME() method is used. * Both, string and bytes32 types are supported. * @param _token address of the token contract. * @return token name as a string or an empty string if none of the methods succeeded. */ function readName(address _token) internal view returns (string) { return _readStringWithFallback(_token, _NAME, _NAME_CAPS); } /** * @dev Reads the symbol property of the provided token. * Either symbol() or SYMBOL() method is used. * Both, string and bytes32 types are supported. * @param _token address of the token contract. * @return token symbol as a string or an empty string if none of the methods succeeded. */ function readSymbol(address _token) internal view returns (string) { return _readStringWithFallback(_token, _SYMBOL, _SYMBOL_CAPS); } /** * @dev Reads the decimals property of the provided token. * Either decimals() or DECIMALS() method is used. * @param _token address of the token contract. * @return token decimals or 0 if none of the methods succeeded. */ function readDecimals(address _token) internal view returns (uint256) { return _readIntWithFallback(_token, _DECIMALS, _DECIMALS_CAPS); } function readTotalSupply(address _token) internal view returns (uint256) { return _readIntFunctionThatMightNotExist(_token, _TOTAL_SUPPLY); } function readTokenURI(address _token, uint256 _tokenId) internal view returns (string) { bytes memory encodedParams = abi.encodeWithSelector(_TOKEN_URI, _tokenId); return _dynamicStringMethodCall(_token, encodedParams); } function _readStringWithFallback(address _contract, bytes4 _selector1, bytes4 _selector2) internal view returns (string) { string memory firstResult = _readStringFunctionThatMightNotExist(_contract, _selector1); if (bytes(firstResult).length > 0) { return firstResult; } return _readStringFunctionThatMightNotExist(_contract, _selector2); } function _readIntWithFallback(address _contract, bytes4 _selector1, bytes4 _selector2) internal view returns (uint256) { uint256 firstResult = _readIntFunctionThatMightNotExist(_contract, _selector1); if (firstResult > 0) { return firstResult; } return _readIntFunctionThatMightNotExist(_contract, _selector2); } function _readStringFunctionThatMightNotExist(address _contract, bytes4 _selector) internal view returns (string) { bytes memory encodedParams = abi.encodeWithSelector(_selector); return _dynamicStringMethodCall(_contract, encodedParams); } function _dynamicStringMethodCall(address _contract, bytes encodedParams) internal view returns (string) { uint256 ptr; uint256 size; assembly { let encodedParams_data := add(0x20, encodedParams) let encodedParams_size := mload(encodedParams) ptr := mload(0x40) staticcall(gas, _contract, encodedParams_data, encodedParams_size, ptr, 32) pop mstore(0x40, add(ptr, returndatasize)) switch gt(returndatasize, 32) case 1 { returndatacopy(mload(0x40), 32, 32) // string length size := mload(mload(0x40)) } default { size := returndatasize // 32 or 0 } } string memory res = new string(size); assembly { if gt(returndatasize, 32) { // load as string returndatacopy(add(res, 32), 64, size) jump(exit) } // solhint-disable if gt(returndatasize, 0) { let i := 0 ptr := mload(ptr) // load bytes32 value mstore(add(res, 32), ptr) // save value in result string for { } gt(ptr, 0) { i := add(i, 1) } { // until string is empty ptr := shl(8, ptr) // shift left by one symbol } mstore(res, i) // save result string length } exit: // solhint-enable } return res; } function _readIntFunctionThatMightNotExist(address _contract, bytes4 selector) internal view returns (uint256) { uint256 decimals; // bytes32 nameBytes = _encodeMethodSignature(); assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 32)) mstore(ptr, selector) if iszero(staticcall(gas, _contract, ptr, 4, ptr, 32)) { mstore(ptr, 0) } decimals := mload(ptr) } return decimals; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/ForeignMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title ForeignMultiAMBErc20ToErc677 * @dev Foreign side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract ForeignMultiAMBErc20ToErc677 is BasicMultiAMBErc20ToErc677 { using SafeERC20 for address; using SafeERC20 for ERC677; /** * @dev Stores the initial parameters of the mediator. * @param _bridgeContract the address of the AMB bridge contract. * @param _mediatorContract the address of the mediator contract on the other network. * @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network. * [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ] * @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network. * [ 0 = executionDailyLimit, 1 = executionMaxPerTx ] * @param _requestGasLimit the gas limit for the message execution. * @param _owner address of the owner of the mediator contract. */ function initialize( address _bridgeContract, address _mediatorContract, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ] uint256 _requestGasLimit, address _owner ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setMediatorContractOnOtherSide(_mediatorContract); _setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); setInitialize(); return isInitialized(); } /** * @dev Executes action on the request to withdraw tokens relayed from the other network * @param _token address of the token contract * @param _recipient address of tokens receiver * @param _value amount of bridged tokens */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal { bytes32 _messageId = messageId(); _token.safeTransfer(_recipient, _value); _setMediatorBalance(_token, mediatorBalance(_token).sub(_value)); emit TokensBridged(_token, _recipient, _value, _messageId); } /** * @dev ERC677 transfer callback function. * @param _from address of tokens sender. * @param _value amount of transferred tokens. * @param _data additional transfer data, can be used for passing alternative receiver address. */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) { if (!lock()) { ERC677 token = ERC677(msg.sender); bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data); } return true; } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20 token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator { require(isTokenRegistered(_token)); _handleBridgedTokens(_token, _recipient, _value); } /** * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract * and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network. * The user should first call Approve method of the ERC677 token. * @param token bridge token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal { // This lock is to prevent calling passMessage twice if a ERC677 token is used. // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract // which will call passMessage. require(!lock()); uint256 balanceBefore = token.balanceOf(address(this)); setLock(true); token.transferFrom(msg.sender, address(this), _value); setLock(false); uint256 balanceDiff = token.balanceOf(address(this)).sub(balanceBefore); require(balanceDiff <= _value); bridgeSpecificActionsOnTokenTransfer(token, msg.sender, balanceDiff, abi.encodePacked(_receiver)); } /** * @dev Executes action on deposit of bridged tokens * @param _token address of the token contract * @param _from address of tokens sender * @param _value requsted amount of bridged tokens * @param _data alternative receiver, if specified */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal { if (lock()) return; require(isTokenAllowed(_token)); bool isKnownToken = isTokenRegistered(_token); if (!isKnownToken) { string memory name = TokenReader.readName(_token); string memory symbol = TokenReader.readSymbol(_token); uint8 decimals = uint8(TokenReader.readDecimals(_token)); require(bytes(name).length > 0 || bytes(symbol).length > 0); _initializeTokenBridgeLimits(_token, decimals); } require(withinLimit(_token, _value)); addTotalSpentPerDay(_token, getCurrentDay(), _value); bytes memory data; address receiver = chooseReceiver(_from, _data); if (isKnownToken) { data = abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, receiver, _value); } else { data = abi.encodeWithSelector( HomeMultiAMBErc20ToErc677(this).deployAndHandleBridgedTokens.selector, _token, name, symbol, decimals, receiver, _value ); } _setMediatorBalance(_token, mediatorBalance(_token).add(_value)); bytes32 _messageId = bridgeContract().requireToPassMessage( mediatorContractOnOtherSide(), data, requestGasLimit() ); setMessageToken(_messageId, _token); setMessageValue(_messageId, _value); setMessageRecipient(_messageId, _from); if (!isKnownToken) { _setTokenRegistrationMessageId(_token, _messageId); } emit TokensBridgingInitiated(_token, _from, _value, _messageId); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) public { super.fixFailedMessage(_messageId); address token = messageToken(_messageId); if (_messageId == tokenRegistrationMessageId(token)) { delete uintStorage[keccak256(abi.encodePacked("dailyLimit", token))]; delete uintStorage[keccak256(abi.encodePacked("maxPerTx", token))]; delete uintStorage[keccak256(abi.encodePacked("minPerTx", token))]; delete uintStorage[keccak256(abi.encodePacked("executionDailyLimit", token))]; delete uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", token))]; _setTokenRegistrationMessageId(token, bytes32(0)); } } /** * @dev Unlock back the amount of tokens that were bridged to the other network but failed. * @param _token address that bridged token contract. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal { _setMediatorBalance(_token, mediatorBalance(_token).sub(_value)); _token.safeTransfer(_recipient, _value); } /** * @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract * without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer) * @param _token address of the token contract. * @param _receiver the address that will receive the tokens on the other network. */ function fixMediatorBalance(address _token, address _receiver) external onlyIfUpgradeabilityOwner validAddress(_receiver) { require(isTokenRegistered(_token)); uint256 balance = ERC677(_token).balanceOf(address(this)); uint256 expectedBalance = mediatorBalance(_token); require(balance > expectedBalance); uint256 diff = balance - expectedBalance; uint256 available = maxAvailablePerTx(_token); require(available > 0); if (diff > available) { diff = available; } addTotalSpentPerDay(_token, getCurrentDay(), diff); _setMediatorBalance(_token, expectedBalance.add(diff)); bytes memory data = abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, diff); bytes32 _messageId = bridgeContract().requireToPassMessage( mediatorContractOnOtherSide(), data, requestGasLimit() ); setMessageToken(_messageId, _token); setMessageValue(_messageId, diff); setMessageRecipient(_messageId, _receiver); } /** * @dev Tells the expected token balance of the contract. * @param _token address of token contract. * @return the current tracked token balance of the contract. */ function mediatorBalance(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))]; } /** * @dev Returns message id where specified token was first seen and deploy on the other side was requested. * @param _token address of token contract. * @return message id of the send message. */ function tokenRegistrationMessageId(address _token) public view returns (bytes32) { return bytes32(uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))]); } /** * @dev Updates expected token balance of the contract. * @param _token address of token contract. * @param _balance the new token balance of the contract. */ function _setMediatorBalance(address _token, uint256 _balance) internal { uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))] = _balance; } /** * @dev Updates message id where specified token was first seen and deploy on the other side was requested. * @param _token address of token contract. * @param _messageId message id of the send message. */ function _setTokenRegistrationMessageId(address _token, bytes32 _messageId) internal { uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))] = uint256(_messageId); } function isTokenAllowed(address _token) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("tokenAllowed", _token))]; } function allowToken(address _token) external onlyOwner { _allowToken(_token); } event TokenAllowed(address indexed token); function _allowToken(address _token) internal { require(!isTokenAllowed(_token)); require(AddressUtils.isContract(_token)); boolStorage[keccak256(abi.encodePacked("tokenAllowed", _token))] = true; emit TokenAllowed(_token); } function disallowToken(address _token) external onlyOwner { _disallowToken(_token); } event TokenDisallowed(address indexed token); function _disallowToken(address _token) internal { require(isTokenAllowed(_token)); require(AddressUtils.isContract(_token)); boolStorage[keccak256(abi.encodePacked("tokenAllowed", _token))] = false; emit TokenDisallowed(_token); } }
Calculates and distributes the amount of fee proportionally between registered reward addresses. _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. _value bridged value, for which fee should be evaluated. return total amount of fee subtracted from the transferred value and distributed between the reward accounts./
function _distributeFee(bytes32 _feeType, address _token, uint256 _value) internal returns (uint256) { uint256 numOfAccounts = rewardAddressCount(); uint256 _fee = calculateFee(_feeType, _token, _value); if (numOfAccounts == 0 || _fee == 0) { return 0; } uint256 feePerAccount = _fee.div(numOfAccounts); uint256 randomAccountIndex; uint256 diff = _fee.sub(feePerAccount.mul(numOfAccounts)); if (diff > 0) { randomAccountIndex = random(numOfAccounts); } address nextAddr = getNextRewardAddress(F_ADDR); require(nextAddr != F_ADDR && nextAddr != address(0)); uint256 i = 0; while (nextAddr != F_ADDR) { uint256 feeToDistribute = feePerAccount; if (diff > 0 && randomAccountIndex == i) { feeToDistribute = feeToDistribute.add(diff); } if (_feeType == HOME_TO_FOREIGN_FEE) { ERC677(_token).transfer(nextAddr, feeToDistribute); IBurnableMintableERC677Token(_token).mint(nextAddr, feeToDistribute); } nextAddr = getNextRewardAddress(nextAddr); require(nextAddr != address(0)); i = i + 1; } return _fee; }
1,401,950
pragma solidity 0.5.6; contract ArianeeWhitelist { function addWhitelistedAddress(uint256 _tokenId, address _address) external; } contract ArianeeStore{ function canTransfer(address _to,address _from,uint256 _tokenId) external returns(bool); function canDestroy(uint256 _tokenId, address _sender) external returns(bool); } import "@0xcert/ethereum-utils-contracts/src/contracts/permission/abilitable.sol"; import "@0xcert/ethereum-utils-contracts/src/contracts/permission/ownable.sol"; import "./Pausable.sol"; import "./ECDSA.sol"; import "@0xcert/ethereum-erc721-contracts/src/contracts/nf-token-metadata-enumerable.sol"; /// @title Contract handling Arianee Certificates. contract ArianeeSmartAsset is NFTokenMetadataEnumerable, Abilitable, Ownable, Pausable { /** * @dev Mapping from token id to URI. */ mapping(uint256 => string) internal idToUri; /** * @dev Mapping from token id to Token Access (0=view, 1=transfer). */ mapping(uint256 => mapping(uint256 => address)) internal tokenAccess; /** * @dev Mapping from token id to TokenImprintUpdate. */ mapping(uint256 => bytes32) internal idToImprint; /** * @dev Mapping from token id to recovery request bool. */ mapping(uint256=>bool) internal recoveryRequest; /** * @dev Mapping from token id to total rewards for this NFT. */ mapping(uint256=>uint256) internal rewards; /** * @dev Mapping from token id to Cert. */ mapping(uint256 => Cert) internal certificate; /** * @dev This emits when a new address is set. */ event SetAddress(string _addressType, address _newAddress); struct Cert { address tokenIssuer; uint256 tokenCreationDate; uint256 tokenRecoveryTimestamp; } /** * @dev Ability to create and hydrate NFT. */ uint8 constant ABILITY_CREATE_ASSET = 2; /** * @dev Error constants. */ string constant CAPABILITY_NOT_SUPPORTED = "007001"; string constant TRANSFERS_DISABLED = "007002"; string constant NOT_VALID_XCERT = "007003"; string constant NFT_ALREADY_SET = "007006"; string constant NOT_OWNER_OR_OPERATOR = "007004"; /** * Interface for all the connected contracts. */ ArianeeWhitelist arianeeWhitelist; ArianeeStore store; /** * @dev This emits when a token is hydrated. */ event Hydrated(uint256 _tokenId, bytes32 _imprint, string _uri, address _initialKey, uint256 _tokenRecoveryTimestamp, bool _initialKeyIsRequestKey, uint256 _tokenCreation); /** * @dev This emits when a issuer request a NFT recovery. */ event RecoveryRequestUpdated(uint256 _tokenId, bool _active); /** * @dev This emits when a NFT is recovered to the issuer. */ event TokenRecovered(uint256 _token); /** * @dev This emits when a NFT's URI is udpated. */ event TokenURIUpdated(uint256 _tokenId, string URI); /** * @dev This emits when a token access is added. */ event TokenAccessAdded(uint256 _tokenId, address _encryptedTokenKey, bool _enable, uint256 _tokenType); /** * @dev This emits when a token access is destroyed. */ event TokenDestroyed(uint256 _tokenId); /** * @dev This emits when the uri base is udpated. */ event SetNewUriBase(string _newUriBase); /** * @dev Check if the msg.sender can operate the NFT. * @param _tokenId ID of the NFT to test. * @param _operator Address to test. */ modifier isOperator(uint256 _tokenId, address _operator) { require(canOperate(_tokenId, _operator), NOT_OWNER_OR_OPERATOR); _; } /** * @dev Check if msg.sender is the issuer of a NFT. * @param _tokenId ID of the NFT to test. */ modifier isIssuer(uint256 _tokenId) { require(msg.sender == certificate[_tokenId].tokenIssuer); _; } /** * @dev Initialize this contract. Acts as a constructor * @param _arianeeWhitelistAddress Adress of the whitelist contract. */ constructor( address _arianeeWhitelistAddress ) public { nftName = "Arianee Smart-Asset"; nftSymbol = "AriaSA"; setWhitelistAddress(_arianeeWhitelistAddress); _setUriBase("https://cert.arianee.org/"); } /** * @notice Change address of the store infrastructure. * @param _storeAddress new address of the store. */ function setStoreAddress(address _storeAddress) external onlyOwner(){ store = ArianeeStore(address(_storeAddress)); emit SetAddress("storeAddress", _storeAddress); } /** * @notice Reserve a NFT at the given ID. * @dev Has to be called through an authorized contract. * @dev Can only be called by an authorized address. * @param _tokenId ID to reserve. * @param _to receiver of the token. * @param _rewards total rewards of this NFT. */ function reserveToken(uint256 _tokenId, address _to, uint256 _rewards) external hasAbilities(ABILITY_CREATE_ASSET) whenNotPaused() { super._create(_to, _tokenId); rewards[_tokenId] = _rewards; } /** * @notice Recover the NFT to the issuer. * @dev only if called by the issuer and if called before the token Recovery Timestamp of the NFT. * @param _tokenId ID of the NFT to recover. */ function recoverTokenToIssuer(uint256 _tokenId) external whenNotPaused() isIssuer(_tokenId) { require(block.timestamp < certificate[_tokenId].tokenRecoveryTimestamp); idToApproval[_tokenId] = certificate[_tokenId].tokenIssuer; _transferFrom(idToOwner[_tokenId], certificate[_tokenId].tokenIssuer, _tokenId); emit TokenRecovered(_tokenId); } /** * @notice Update a recovery request (doesn't transfer the NFT). * @dev Works only if called by the issuer. * @param _tokenId ID of the NFT to recover. * @param _active boolean to active or unactive the request. */ function updateRecoveryRequest(uint256 _tokenId, bool _active) external whenNotPaused() isIssuer(_tokenId){ recoveryRequest[_tokenId] = _active; emit RecoveryRequestUpdated(_tokenId, _active); } /** * @notice Valid a recovery request and transfer the NFT to the issuer. * @dev only if the request is active and if called by the owner of the contract. * @param _tokenId Id of the NFT to recover. */ function validRecoveryRequest(uint256 _tokenId) external onlyOwner(){ require(recoveryRequest[_tokenId]); recoveryRequest[_tokenId] = false; idToApproval[_tokenId] = owner; _transferFrom(idToOwner[_tokenId], certificate[_tokenId].tokenIssuer, _tokenId); emit RecoveryRequestUpdated(_tokenId, false); emit TokenRecovered(_tokenId); } /** * @notice External function to update the tokenURI. * @notice Can only be called by the NFT's issuer. * @param _tokenId ID of the NFT to edit. * @param _uri New URI for the certificate. */ function updateTokenURI(uint256 _tokenId, string calldata _uri) external isIssuer(_tokenId) whenNotPaused() { require(idToOwner[_tokenId] != address(0), NOT_VALID_XCERT); idToUri[_tokenId] = _uri; emit TokenURIUpdated(_tokenId, _uri); } /** * @notice Add a token access to a NFT. * @notice can only be called by an NFT's operator. * @param _tokenId ID of the NFT. * @param _key Public address of the token to encode the hash with. * @param _enable Enable or disable the token access. * @param _tokenType Type of token access (0=view, 1=tranfer). * @return true. */ function addTokenAccess(uint256 _tokenId, address _key, bool _enable, uint256 _tokenType) external isOperator(_tokenId, msg.sender) whenNotPaused() { require(_tokenType>0); if (_enable) { tokenAccess[_tokenId][_tokenType] = _key; } else { tokenAccess[_tokenId][_tokenType] = address(0); } emit TokenAccessAdded(_tokenId, _key, _enable, _tokenType); } /** * @notice Transfers the ownership of a NFT to another address * @notice Requires to send the correct tokenKey and the NFT has to be requestable * @dev Has to be called through an authorized contract. * @dev approve the requester if _tokenKey is valid to allow transferFrom without removing ERC721 compliance. * @param _tokenId ID of the NFT to transfer. * @param _hash Hash of tokenId + newOwner address. * @param _keepRequestToken If false erase the access token of the NFT. * @param _newOwner Address of the new owner of the NFT. * @return total rewards of this NFT. */ function requestToken(uint256 _tokenId, bytes32 _hash, bool _keepRequestToken, address _newOwner, bytes calldata _signature) external hasAbilities(ABILITY_CREATE_ASSET) whenNotPaused() returns(uint256 reward){ require(isTokenValid(_tokenId, _hash, 1, _signature)); bytes32 message = keccak256(abi.encode(_tokenId, _newOwner)); require(ECDSA.toEthSignedMessageHash(message) == _hash); idToApproval[_tokenId] = msg.sender; if(!_keepRequestToken){ tokenAccess[_tokenId][1] = address(0); } _transferFrom(idToOwner[_tokenId], _newOwner, _tokenId); reward = rewards[_tokenId]; delete rewards[_tokenId]; } /** * @notice Destroy a token. * @notice Can only be called by the issuer. * @param _tokenId to destroy. */ function destroy(uint256 _tokenId) external whenNotPaused() { require(store.canDestroy(_tokenId, msg.sender)); _destroy(_tokenId); idToImprint[_tokenId] = ""; idToUri[_tokenId] = ""; tokenAccess[_tokenId][0] = address(0); tokenAccess[_tokenId][1] = address(0); rewards[_tokenId] = 0; Cert memory _emptyCert = Cert({ tokenIssuer : address(0), tokenCreationDate: 0, tokenRecoveryTimestamp: 0 }); certificate[_tokenId] = _emptyCert; emit TokenDestroyed(_tokenId); } /** * @notice return the URI of a NFT. * @param _tokenId uint256 ID of the NFT. * @return URI of the NFT. */ function tokenURI(uint256 _tokenId) external view returns (string memory){ if(bytes(idToUri[_tokenId]).length > 0){ return idToUri[_tokenId]; } else{ return string(abi.encodePacked(uriBase, _uint2str(_tokenId))); } } /** * @notice Check if a token is requestable. * @param _tokenId uint256 ID of the token to check. * @return True if the NFT is requestable. */ function isRequestable(uint256 _tokenId) external view returns (bool) { return tokenAccess[_tokenId][1] != address(0); } /** * @notice The issuer address for a given Token ID. * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId Id for which we want the issuer. * @return Issuer address of _tokenId. */ function issuerOf(uint256 _tokenId) external view returns(address _tokenIssuer){ require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _tokenIssuer = certificate[_tokenId].tokenIssuer; } /** * @notice The imprint for a given Token ID. * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId Id for which we want the imprint. * @return Imprint address of _tokenId. */ function tokenImprint(uint256 _tokenId) external view returns(bytes32 _imprint){ require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _imprint = idToImprint[_tokenId]; } /** * @notice The creation date for a given Token ID. * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId Id for which we want the creation date. * @return Creation date of _tokenId. */ function tokenCreation(uint256 _tokenId) external view returns(uint256 _tokenCreation){ require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _tokenCreation = certificate[_tokenId].tokenCreationDate; } /** * @notice The Token Access for a given Token ID and token type. * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId Id for which we want the token access. * @param _tokenType for which we want the token access. * @return Token access of _tokenId. */ function tokenHashedAccess(uint256 _tokenId, uint256 _tokenType) external view returns(address _tokenAccess){ require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _tokenAccess = tokenAccess[_tokenId][_tokenType]; } /** * @notice The recovery timestamp for a given Token ID. * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId Id for which we want the recovery timestamp. * @return Recovery timestamp of _tokenId. */ function tokenRecoveryDate(uint256 _tokenId) external view returns(uint256 _tokenRecoveryTimestamp){ require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _tokenRecoveryTimestamp = certificate[_tokenId].tokenRecoveryTimestamp; } /** * @notice The recovery timestamp for a given Token ID. * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId Id for which we want the recovery timestamp. * @return Recovery timestamp of _tokenId. */ function recoveryRequestOpen(uint256 _tokenId) external view returns(bool _recoveryRequest){ require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _recoveryRequest = recoveryRequest[_tokenId]; } /** * @notice The rewards for a given Token ID. * @param _tokenId Id for which we want the rewards. * @return Rewards of _tokenId. */ function getRewards(uint256 _tokenId) external view returns(uint256){ return rewards[_tokenId]; } /** * @notice Check if an operator is valid for a given NFT. * @param _tokenId nft to check. * @param _operator operator to check. * @return true if operator is valid. */ function canOperate(uint256 _tokenId, address _operator) public view returns (bool){ address tokenOwner = idToOwner[_tokenId]; return tokenOwner == _operator || ownerToOperators[tokenOwner][_operator]; } /** * @notice Change the base URI address. * @param _newURIBase the new URI base address. */ function setUriBase(string memory _newURIBase) public onlyOwner(){ _setUriBase(_newURIBase); emit SetNewUriBase(_newURIBase); } /** * @notice Change address of the whitelist. * @param _whitelistAddres new address of the whitelist. */ function setWhitelistAddress(address _whitelistAddres) public onlyOwner(){ arianeeWhitelist = ArianeeWhitelist(address(_whitelistAddres)); emit SetAddress("whitelistAddress", _whitelistAddres); } /** * @notice Specify information on a reserved NFT. * @dev to be called through an authorized contract. * @dev Can only be called once and by an NFT's operator. * @param _tokenId ID of the NFT to modify. * @param _imprint Proof of the certification. * @param _uri URI of the JSON certification. * @param _initialKey Initial key. * @param _tokenRecoveryTimestamp Limit date for the issuer to be able to transfer back the NFT. * @param _initialKeyIsRequestKey If true set initial key as request key. */ function hydrateToken(uint256 _tokenId, bytes32 _imprint, string memory _uri, address _initialKey, uint256 _tokenRecoveryTimestamp, bool _initialKeyIsRequestKey, address _owner) public hasAbilities(ABILITY_CREATE_ASSET) whenNotPaused() isOperator(_tokenId, _owner) returns(uint256){ require(!(certificate[_tokenId].tokenCreationDate > 0), NFT_ALREADY_SET); uint256 _tokenCreation = block.timestamp; tokenAccess[_tokenId][0] = _initialKey; idToImprint[_tokenId] = _imprint; idToUri[_tokenId] = _uri; arianeeWhitelist.addWhitelistedAddress(_tokenId, _owner); if (_initialKeyIsRequestKey) { tokenAccess[_tokenId][1] = _initialKey; } Cert memory _cert = Cert({ tokenIssuer : _owner, tokenCreationDate: _tokenCreation, tokenRecoveryTimestamp :_tokenRecoveryTimestamp }); certificate[_tokenId] = _cert; emit Hydrated(_tokenId, _imprint, _uri, _initialKey, _tokenRecoveryTimestamp, _initialKeyIsRequestKey, _tokenCreation); return rewards[_tokenId]; } /** * @notice Check if a token access is valid. * @param _tokenId ID of the NFT to validate. * @param _hash Hash of tokenId + newOwner address. * @param _tokenType Type of token access (0=view, 1=transfer). */ function isTokenValid(uint256 _tokenId, bytes32 _hash, uint256 _tokenType, bytes memory _signature) public view returns (bool){ return ECDSA.recover(_hash, _signature) == tokenAccess[_tokenId][_tokenType]; } /** * @notice Legacy function of TransferFrom, add the new owner as whitelisted for the message. * @dev Require the store to approve the transfer. */ function _transferFrom(address _to, address _from, uint256 _tokenId) internal { require(store.canTransfer(_to, _from, _tokenId)); super._transferFrom(_to, _from, _tokenId); arianeeWhitelist.addWhitelistedAddress(_tokenId, _to); } }
The recovery timestamp for a given Token ID. Throws if `_tokenId` is not a valid NFT. _tokenId Id for which we want the recovery timestamp. return Recovery timestamp of _tokenId./
function tokenRecoveryDate(uint256 _tokenId) external view returns(uint256 _tokenRecoveryTimestamp){ require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _tokenRecoveryTimestamp = certificate[_tokenId].tokenRecoveryTimestamp; }
1,831,614
// Sources flattened with hardhat v2.6.4 https://hardhat.org // Etherscan verify via api is broken right now it appears // File @openzeppelin/contracts/utils/Strings.sol@v4.0.0 // 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); } } // File @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol@v4.3.2 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; } } } // File @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol@v4.3.2 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 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; } // File @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol@v4.3.2 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 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; } // File contracts/interfaces/IRegistrar.sol interface IRegistrar { function transferFrom( address from, address to, uint256 tokenId ) external; function registerDomainAndSend( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external returns (uint256); function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol@v4.3.2 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 MerkleProofUpgradeable { /** * @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; } } // File contracts/WolfSale.sol /** Created 4/5/22 Intended for the Wolf Beasts Sale Functionality: - Transfer Sale - Pre-minted NFT's transferred from holder wallet to buyer - Private Sale - Variable sale count per user - Public Sale - Sells up to (3000) NFT's in public sale 'privateSaleDuration' == 'privateSaleDuration' */ contract WolfSale is Initializable, OwnableUpgradeable { // zNS Registrar IRegistrar public zNSRegistrar; event RefundedEther(address buyer, uint256 amount); event SaleStarted(uint256 block); // Price of each domain to be sold uint256 public salePrice; // The wallet to transfer proceeds to address public sellerWallet; // Number of domains sold so far uint256 public domainsSold; // Indicating whether the sale has started or not bool public saleStarted; // The block number that a sale started on uint256 public saleStartBlock; // If a sale has been paused bool public paused; // Merkle root data to verify on private sale bytes32 public privateSaleMerkleRoot; // Time in blocks that the privatesale will occur uint256 public privateSaleDuration; // Mapping to keep track of how many domains an account has purchased so far mapping(address => uint256) public domainsPurchasedByAccount; // How many domains for sale during private sale uint256 public privateSaleQuantity; // How many domains for sale during public sale uint256 public publicSaleQuantity; // The wallet that holds the NFT's to transfer address public holderWallet; function __WolfSale_init( uint256 price_, IRegistrar zNSRegistrar_, address sellerWallet_, uint256 privateSaleDuration_, uint256 privateSaleQuantity_, uint256 publicSaleQuantity_, bytes32 merkleRoot_, address holderWallet_ ) public initializer { salePrice = price_; zNSRegistrar = zNSRegistrar_; sellerWallet = sellerWallet_; privateSaleDuration = privateSaleDuration_; privateSaleQuantity = privateSaleQuantity_; publicSaleQuantity = publicSaleQuantity_; privateSaleMerkleRoot = merkleRoot_; holderWallet = holderWallet_; __Ownable_init(); } // Start the sale if not started function startSale() external onlyOwner { require(!saleStarted, "Sale already started"); saleStarted = true; saleStartBlock = block.number; emit SaleStarted(saleStartBlock); } // Stop the sale if started function stopSale() external onlyOwner { require(saleStarted, "Sale not started"); saleStarted = false; } // Forces the sale to go public immediately function forcePublicSale() external onlyOwner { require(saleStarted, "Sale not started"); privateSaleDuration = block.number - saleStartBlock; } // Update the data that acts as the merkle root function setMerkleRoot(bytes32 root) external onlyOwner { require(privateSaleMerkleRoot != root, "same root"); privateSaleMerkleRoot = root; } // Pause a sale function setPauseStatus(bool pauseStatus) external onlyOwner { require(paused != pauseStatus, "No state change"); paused = pauseStatus; } // Set the price of this sale function setSalePrice(uint256 price) external onlyOwner { require(salePrice != price, "No price change"); salePrice = price; } // Modify the address of the seller wallet function setSellerWallet(address wallet) external onlyOwner { require(wallet != sellerWallet, "Same Wallet"); sellerWallet = wallet; } function setHolderWallet(address wallet) external onlyOwner { require(holderWallet != wallet, "no state change"); holderWallet = wallet; } // Update the number of blocks that the sale will occur function setSaleDuration(uint256 durationInBlocks) external onlyOwner { require(privateSaleDuration != durationInBlocks, "No state change"); privateSaleDuration = durationInBlocks; } function setSaleQuantities(uint256 privateSale, uint256 publicSale) external onlyOwner { require( privateSale != privateSaleQuantity || publicSale != publicSaleQuantity, "No state change" ); if (privateSale != privateSaleQuantity) { privateSaleQuantity = privateSale; } if (publicSale != publicSaleQuantity) { publicSaleQuantity = publicSale; } } // Purchase `count` domains // Not the `purchaseLimit` you provide must be // less than or equal to what is in the private sale function purchaseDomains( uint8 count, uint256 index, uint256 purchaseLimit, bytes32[] calldata merkleProof ) public payable { _canAccountPurchase(msg.sender, count, purchaseLimit); _requireVariableMerkleProof(index, purchaseLimit, merkleProof); _purchaseDomains(count); } // Purchasing during the public sale function purchaseDomainsPublicSale(uint8 count) public payable { bool inPublicSale = block.number > saleStartBlock + privateSaleDuration; require(inPublicSale, "Not public sale yet"); _canAccountPurchase(msg.sender, count, 0); _purchaseDomains(count); } // This is presuming that the only tokens in the registrar will be those created for this sale. // If this is untrue, this is likely not a good contract to use for this sale. function getIDByIndex(uint256 index) public view returns (uint256) { return zNSRegistrar.tokenByIndex(index); } function numberForSaleForCurrentPhase() public view returns (uint256) { // figure out whether in private / public sale bool inPublicSale = block.number > saleStartBlock + privateSaleDuration; if (inPublicSale) { return publicSaleQuantity; } return privateSaleQuantity; } function _canAccountPurchase( address account, uint8 count, uint256 purchaseLimit ) internal view { require(count > 0, "Zero purchase count"); require( domainsSold < numberForSaleForCurrentPhase(), "No domains left for sale" ); bool inPublicSale = block.number > saleStartBlock + privateSaleDuration; if (!inPublicSale) { require( domainsPurchasedByAccount[account] + count <= purchaseLimit, "Purchasing beyond limit." ); } require(msg.value >= salePrice * count, "Not enough funds in purchase"); require(!paused, "paused"); require(saleStarted, "Sale hasn't started or has ended"); } function _purchaseDomains(uint8 count) internal { uint256 numPurchased = _reserveDomainsForPurchase(count); uint256 proceeds = salePrice * numPurchased; _sendPayment(proceeds); _sendDomains(numPurchased); } function _reserveDomainsForPurchase(uint8 count) internal returns (uint256) { uint256 numPurchased = count; uint256 numForSale = numberForSaleForCurrentPhase(); // If we would are trying to purchase more than is available, purchase the remainder if (domainsSold + count > numForSale) { numPurchased = numForSale - domainsSold; } domainsSold += numPurchased; // Update number of domains this account has purchased // This is done before minting domains or sending any eth to prevent // a re-entrance attack through a recieve() or a safe transfer callback domainsPurchasedByAccount[msg.sender] = domainsPurchasedByAccount[msg.sender] + numPurchased; return numPurchased; } // Transfer funds to the buying user, refunding if necessary function _sendPayment(uint256 proceeds) internal { payable(sellerWallet).transfer(proceeds); // Send refund if neceesary for any unpurchased domains if (msg.value - proceeds > 0) { payable(msg.sender).transfer(msg.value - proceeds); emit RefundedEther(msg.sender, msg.value - proceeds); } } function _sendDomains(uint256 numPurchased) internal { // Mint the domains after they have been purchased for (uint256 i = 0; i < numPurchased; ++i) { // At this point, domainsSold will already assume these domains are sold uint256 index = domainsSold - numPurchased + i; zNSRegistrar.transferFrom( address(holderWallet), msg.sender, zNSRegistrar.tokenByIndex(index) ); } } function _requireVariableMerkleProof( uint256 index, uint256 quantity, bytes32[] calldata merkleProof ) internal view { bytes32 node = keccak256(abi.encodePacked(index, msg.sender, quantity)); require( MerkleProofUpgradeable.verify(merkleProof, privateSaleMerkleRoot, node), "Invalid Merkle Proof" ); } }
Mint the domains after they have been purchased At this point, domainsSold will already assume these domains are sold
function _sendDomains(uint256 numPurchased) internal { for (uint256 i = 0; i < numPurchased; ++i) { uint256 index = domainsSold - numPurchased + i; zNSRegistrar.transferFrom( address(holderWallet), msg.sender, zNSRegistrar.tokenByIndex(index) ); } }
10,004,952
./full_match/43113/0xf30298fe66FEbCbbEcF2f79EAdDaB16F2Ad02023/sources/docs.chain.link/samples/PriceFeeds/PriceConsumerMuliple.sol
Returns the latest price/
function getLatestPrice(uint8 decimal) public view returns (priceStrut[] memory) { priceStrut[] memory prices = new priceStrut[](5); prices[0] = priceStrut("AVAX/USD", getPrice(avalance_avax_usd_price_feed, decimal)); prices[1] = priceStrut("AVAX/BTC", getDerivedPrice(avalance_avax_usd_price_feed,avalance_btc_usd_price_feed, decimal)); prices[2] = priceStrut("AVAX/ETH", getDerivedPrice(avalance_avax_usd_price_feed,avalance_eth_usd_price_feed, decimal)); prices[3] = priceStrut("AVAX/USDT", getDerivedPrice(avalance_avax_usd_price_feed,avalance_usdt_usd_price_feed, decimal)); prices[4] = priceStrut("AVAX/USDT", getDerivedPrice(avalance_avax_usd_price_feed,avalance_link_usd_price_feed, decimal)); return prices; }
7,163,662
/** *Submitted for verification at Etherscan.io on 2021-10-29 */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; /* Copyright 2019 ZeroEx Intl. 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. */ // solhint-disable // @dev Interface of the asset proxy's assetData. // The asset proxies take an ABI encoded `bytes assetData` as argument. // This argument is ABI encoded as one of the methods of this interface. interface IAssetData { /// @dev Function signature for encoding ERC20 assetData. /// @param tokenAddress Address of ERC20Token contract. function ERC20Token(address tokenAddress) external; /// @dev Function signature for encoding ERC721 assetData. /// @param tokenAddress Address of ERC721 token contract. /// @param tokenId Id of ERC721 token to be transferred. function ERC721Token( address tokenAddress, uint256 tokenId ) external; /// @dev Function signature for encoding ERC1155 assetData. /// @param tokenAddress Address of ERC1155 token contract. /// @param tokenIds Array of ids of tokens to be transferred. /// @param values Array of values that correspond to each token id to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param callbackData Extra data to be passed to receiver's `onERC1155Received` callback function. function ERC1155Assets( address tokenAddress, uint256[] calldata tokenIds, uint256[] calldata values, bytes calldata callbackData ) external; /// @dev Function signature for encoding MultiAsset assetData. /// @param values Array of amounts that correspond to each asset to be transferred. /// Note that each value will be multiplied by the amount being filled in the order before transferring. /// @param nestedAssetData Array of assetData fields that will be be dispatched to their correspnding AssetProxy contract. function MultiAsset( uint256[] calldata values, bytes[] calldata nestedAssetData ) external; /// @dev Function signature for encoding StaticCall assetData. /// @param staticCallTargetAddress Address that will execute the staticcall. /// @param staticCallData Data that will be executed via staticcall on the staticCallTargetAddress. /// @param expectedReturnDataHash Keccak-256 hash of the expected staticcall return data. function StaticCall( address staticCallTargetAddress, bytes calldata staticCallData, bytes32 expectedReturnDataHash ) external; /// @dev Function signature for encoding ERC20Bridge assetData. /// @param tokenAddress Address of token to transfer. /// @param bridgeAddress Address of the bridge contract. /// @param bridgeData Arbitrary data to be passed to the bridge contract. function ERC20Bridge( address tokenAddress, address bridgeAddress, bytes calldata bridgeData ) external; } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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. */ library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } library LibOrder { using LibOrder for Order; // Hash for the EIP712 Order Schema: // keccak256(abi.encodePacked( // "Order(", // "address makerAddress,", // "address takerAddress,", // "address feeRecipientAddress,", // "address senderAddress,", // "uint256 makerAssetAmount,", // "uint256 takerAssetAmount,", // "uint256 makerFee,", // "uint256 takerFee,", // "uint256 expirationTimeSeconds,", // "uint256 salt,", // "bytes makerAssetData,", // "bytes takerAssetData,", // "bytes makerFeeAssetData,", // "bytes takerFeeAssetData", // ")" // )) bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH = 0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534; // A valid order remains fillable until it is expired, fully filled, or cancelled. // An order's status is unaffected by external factors, like account balances. enum OrderStatus { INVALID, // Default value INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount FILLABLE, // Order is fillable EXPIRED, // Order has already expired FULLY_FILLED, // Order is fully filled CANCELLED // Order has been cancelled } // solhint-disable max-line-length /// @dev Canonical order structure. struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled. uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy. bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy. bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy. } // solhint-enable max-line-length /// @dev Order information returned by `getOrderInfo()`. struct OrderInfo { OrderStatus orderStatus; // Status that describes order's validity and fillability. bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash). uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled. } /// @dev Calculates the EIP712 typed data hash of an order with a given domain separator. /// @param order The order structure. /// @return EIP712 typed data hash of the order. function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 orderHash) { orderHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, order.getStructHash() ); return orderHash; } /// @dev Calculates EIP712 hash of the order struct. /// @param order The order structure. /// @return EIP712 hash of the order struct. function getStructHash(Order memory order) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH; bytes memory makerAssetData = order.makerAssetData; bytes memory takerAssetData = order.takerAssetData; bytes memory makerFeeAssetData = order.makerFeeAssetData; bytes memory takerFeeAssetData = order.takerFeeAssetData; // Assembly for more efficiently computing: // keccak256(abi.encodePacked( // EIP712_ORDER_SCHEMA_HASH, // uint256(order.makerAddress), // uint256(order.takerAddress), // uint256(order.feeRecipientAddress), // uint256(order.senderAddress), // order.makerAssetAmount, // order.takerAssetAmount, // order.makerFee, // order.takerFee, // order.expirationTimeSeconds, // order.salt, // keccak256(order.makerAssetData), // keccak256(order.takerAssetData), // keccak256(order.makerFeeAssetData), // keccak256(order.takerFeeAssetData) // )); assembly { // Assert order offset (this is an internal error that should never be triggered) if lt(order, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(order, 32) let pos2 := add(order, 320) let pos3 := add(order, 352) let pos4 := add(order, 384) let pos5 := add(order, 416) // Backup let temp1 := mload(pos1) let temp2 := mload(pos2) let temp3 := mload(pos3) let temp4 := mload(pos4) let temp5 := mload(pos5) // Hash in place mstore(pos1, schemaHash) mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData result := keccak256(pos1, 480) // Restore mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3) mstore(pos4, temp4) mstore(pos5, temp5) } return result; } } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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. */ library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } library LibSafeMathRichErrors { // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, MULTIPLICATION_OVERFLOW, SUBTRACTION_UNDERFLOW, DIVISION_BY_ZERO } enum DowncastErrorCodes { VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96 } // solhint-disable func-name-mixedcase function Uint256BinOpError( BinOpErrorCodes errorCode, uint256 a, uint256 b ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b ); } function Uint256DowncastError( DowncastErrorCodes errorCode, uint256 a ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a ); } } library LibSafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } 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; } } library LibMathRichErrors { // bytes4(keccak256("DivisionByZeroError()")) bytes internal constant DIVISION_BY_ZERO_ERROR = hex"a791837c"; // bytes4(keccak256("RoundingError(uint256,uint256,uint256)")) bytes4 internal constant ROUNDING_ERROR_SELECTOR = 0x339f3de2; // solhint-disable func-name-mixedcase function DivisionByZeroError() internal pure returns (bytes memory) { return DIVISION_BY_ZERO_ERROR; } function RoundingError( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ROUNDING_ERROR_SELECTOR, numerator, denominator, target ); } } library LibMath { using LibSafeMath for uint256; /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorFloor( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function safeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorCeil( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function getPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } /// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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. */ library LibBytesRichErrors { enum InvalidByteOperationErrorCodes { FromLessThanOrEqualsToRequired, ToLessThanOrEqualsLengthRequired, LengthGreaterThanZeroRequired, LengthGreaterThanOrEqualsFourRequired, LengthGreaterThanOrEqualsTwentyRequired, LengthGreaterThanOrEqualsThirtyTwoRequired, LengthGreaterThanOrEqualsNestedBytesLengthRequired, DestinationLengthGreaterThanOrEqualSourceLengthRequired } // bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)")) bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR = 0x28006595; // solhint-disable func-name-mixedcase function InvalidByteOperationError( InvalidByteOperationErrorCodes errorCode, uint256 offset, uint256 required ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INVALID_BYTE_OPERATION_ERROR_SELECTOR, errorCode, offset, required ); } } library LibBytes { using LibBytes for bytes; /// @dev Gets the memory address for a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of byte array. This /// points to the header of the byte array which contains /// the length. function rawAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := input } return memoryAddress; } /// @dev Gets the memory address for the contents of a byte array. /// @param input Byte array to lookup. /// @return memoryAddress Memory address of the contents of the byte array. function contentAddress(bytes memory input) internal pure returns (uint256 memoryAddress) { assembly { memoryAddress := add(input, 32) } return memoryAddress; } /// @dev Copies `length` bytes from memory location `source` to `dest`. /// @param dest memory address to copy bytes to. /// @param source memory address to copy bytes from. /// @param length number of bytes to copy. function memCopy( uint256 dest, uint256 source, uint256 length ) internal pure { if (length < 32) { // Handle a partial word by reading destination and masking // off the bits we are interested in. // This correctly handles overlap, zero lengths and source == dest assembly { let mask := sub(exp(256, sub(32, length)), 1) let s := and(mload(source), not(mask)) let d := and(mload(dest), mask) mstore(dest, or(s, d)) } } else { // Skip the O(length) loop when source == dest. if (source == dest) { return; } // For large copies we copy whole words at a time. The final // word is aligned to the end of the range (instead of after the // previous) to handle partial words. So a copy will look like this: // // #### // #### // #### // #### // // We handle overlap in the source and destination range by // changing the copying direction. This prevents us from // overwriting parts of source that we still need to copy. // // This correctly handles source == dest // if (source > dest) { assembly { // We subtract 32 from `sEnd` and `dEnd` because it // is easier to compare with in the loop, and these // are also the addresses we need for copying the // last bytes. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the last 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the last bytes in // source already due to overlap. let last := mload(sEnd) // Copy whole words front to back // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} lt(source, sEnd) {} { mstore(dest, mload(source)) source := add(source, 32) dest := add(dest, 32) } // Write the last 32 bytes mstore(dEnd, last) } } else { assembly { // We subtract 32 from `sEnd` and `dEnd` because those // are the starting points when copying a word at the end. length := sub(length, 32) let sEnd := add(source, length) let dEnd := add(dest, length) // Remember the first 32 bytes of source // This needs to be done here and not after the loop // because we may have overwritten the first bytes in // source already due to overlap. let first := mload(source) // Copy whole words back to front // We use a signed comparisson here to allow dEnd to become // negative (happens when source and dest < 32). Valid // addresses in local memory will never be larger than // 2**255, so they can be safely re-interpreted as signed. // Note: the first check is always true, // this could have been a do-while loop. // solhint-disable-next-line no-empty-blocks for {} slt(dest, dEnd) {} { mstore(dEnd, mload(sEnd)) sEnd := sub(sEnd, 32) dEnd := sub(dEnd, 32) } // Write the first 32 bytes mstore(dest, first) } } } } /// @dev Returns a slices from a byte array. /// @param b The byte array to take a slice from. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) function slice( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure and copy contents result = new bytes(to - from); memCopy( result.contentAddress(), b.contentAddress() + from, result.length ); return result; } /// @dev Returns a slice from a byte array without preserving the input. /// @param b The byte array to take a slice from. Will be destroyed in the process. /// @param from The starting index for the slice (inclusive). /// @param to The final index for the slice (exclusive). /// @return result The slice containing bytes at indices [from, to) /// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted. function sliceDestructive( bytes memory b, uint256 from, uint256 to ) internal pure returns (bytes memory result) { // Ensure that the from and to positions are valid positions for a slice within // the byte array that is being used. if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); } if (to > b.length) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired, to, b.length )); } // Create a new bytes structure around [from, to) in-place. assembly { result := add(b, from) mstore(result, sub(to, from)) } return result; } /// @dev Pops the last byte off of a byte array by modifying its length. /// @param b Byte array that will be modified. /// @return The byte that was popped off. function popLastByte(bytes memory b) internal pure returns (bytes1 result) { if (b.length == 0) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired, b.length, 0 )); } // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /// @dev Tests equality of two byte arrays. /// @param lhs First byte array to compare. /// @param rhs Second byte array to compare. /// @return True if arrays are the same. False otherwise. function equals( bytes memory lhs, bytes memory rhs ) internal pure returns (bool equal) { // Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare. // We early exit on unequal lengths, but keccak would also correctly // handle this. return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs); } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } /// @dev Writes an address into a specific position in a byte array. /// @param b Byte array to insert address into. /// @param index Index in byte array of address. /// @param input Address to put into byte array. function writeAddress( bytes memory b, uint256 index, address input ) internal pure { if (b.length < index + 20) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired, b.length, index + 20 // 20 is length of address )); } // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Store address into array memory assembly { // The address occupies 20 bytes and mstore stores 32 bytes. // First fetch the 32-byte word where we'll be storing the address, then // apply a mask so we have only the bytes in the word that the address will not occupy. // Then combine these bytes with the address and store the 32 bytes back to memory with mstore. // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address let neighbors := and( mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000 ) // Make sure input address is clean. // (Solidity does not guarantee this) input := and(input, 0xffffffffffffffffffffffffffffffffffffffff) // Store the neighbors and address into memory mstore(add(b, index), xor(input, neighbors)) } } /// @dev Reads a bytes32 value from a position in a byte array. /// @param b Byte array containing a bytes32 value. /// @param index Index in byte array of bytes32 value. /// @return bytes32 value from byte array. function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /// @dev Writes a bytes32 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input bytes32 to put into byte array. function writeBytes32( bytes memory b, uint256 index, bytes32 input ) internal pure { if (b.length < index + 32) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired, b.length, index + 32 )); } // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { mstore(add(b, index), input) } } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /// @dev Writes a uint256 into a specific position in a byte array. /// @param b Byte array to insert <input> into. /// @param index Index in byte array of <input>. /// @param input uint256 to put into byte array. function writeUint256( bytes memory b, uint256 index, uint256 input ) internal pure { writeBytes32(b, index, bytes32(input)); } /// @dev Reads an unpadded bytes4 value from a position in a byte array. /// @param b Byte array containing a bytes4 value. /// @param index Index in byte array of bytes4 value. /// @return bytes4 value from byte array. function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { if (b.length < index + 4) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, b.length, index + 4 )); } // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /// @dev Writes a new length to a byte array. /// Decreasing length will lead to removing the corresponding lower order bytes from the byte array. /// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array. /// @param b Bytes array to write new length to. /// @param length New length of byte array. function writeLength(bytes memory b, uint256 length) internal pure { assembly { mstore(b, length) } } } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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 IERC20Token { // solhint-disable 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 ); /// @dev 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 True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev 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 True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `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 wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @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) external view returns (uint256); } library LibERC20Token { bytes constant private DECIMALS_CALL_DATA = hex"313ce567"; /// @dev Calls `IERC20Token(token).approve()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param allowance The allowance to set. function approve( address token, address spender, uint256 allowance ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).approve.selector, spender, allowance ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).approve()` and sets the allowance to the /// maximum if the current approval is not already >= an amount. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param spender The address that receives an allowance. /// @param amount The minimum allowance needed. function approveIfBelow( address token, address spender, uint256 amount ) internal { if (IERC20Token(token).allowance(address(this), spender) < amount) { approve(token, spender, uint256(-1)); } } /// @dev Calls `IERC20Token(token).transfer()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transfer( address token, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transfer.selector, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Calls `IERC20Token(token).transferFrom()`. /// Reverts if `false` is returned or if the return /// data length is nonzero and not 32 bytes. /// @param token The address of the token contract. /// @param from The owner of the tokens. /// @param to The address that receives the tokens /// @param amount Number of tokens to transfer. function transferFrom( address token, address from, address to, uint256 amount ) internal { bytes memory callData = abi.encodeWithSelector( IERC20Token(0).transferFrom.selector, from, to, amount ); _callWithOptionalBooleanResult(token, callData); } /// @dev Retrieves the number of decimals for a token. /// Returns `18` if the call reverts. /// @param token The address of the token contract. /// @return tokenDecimals The number of decimals places for the token. function decimals(address token) internal view returns (uint8 tokenDecimals) { tokenDecimals = 18; (bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA); if (didSucceed && resultData.length == 32) { tokenDecimals = uint8(LibBytes.readUint256(resultData, 0)); } } /// @dev Retrieves the allowance for a token, owner, and spender. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @param spender The address the spender. /// @return allowance The allowance for a token, owner, and spender. function allowance(address token, address owner, address spender) internal view returns (uint256 allowance_) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).allowance.selector, owner, spender ) ); if (didSucceed && resultData.length == 32) { allowance_ = LibBytes.readUint256(resultData, 0); } } /// @dev Retrieves the balance for a token owner. /// Returns `0` if the call reverts. /// @param token The address of the token contract. /// @param owner The owner of the tokens. /// @return balance The token balance of an owner. function balanceOf(address token, address owner) internal view returns (uint256 balance) { (bool didSucceed, bytes memory resultData) = token.staticcall( abi.encodeWithSelector( IERC20Token(0).balanceOf.selector, owner ) ); if (didSucceed && resultData.length == 32) { balance = LibBytes.readUint256(resultData, 0); } } /// @dev Executes a call on address `target` with calldata `callData` /// and asserts that either nothing was returned or a single boolean /// was returned equal to `true`. /// @param target The call target. /// @param callData The abi-encoded call data. function _callWithOptionalBooleanResult( address target, bytes memory callData ) private { (bool didSucceed, bytes memory resultData) = target.call(callData); if (didSucceed) { if (resultData.length == 0) { return; } if (resultData.length == 32) { uint256 result = LibBytes.readUint256(resultData, 0); if (result == 1) { return; } } } LibRichErrors.rrevert(resultData); } } /* Copyright 2019 ZeroEx Intl. 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 IERC721Token { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// perator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) public; /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) public view returns (address); /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) public view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) public view returns (bool); } /* Copyright 2019 ZeroEx Intl. 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. */ /// @title ERC-1155 Multi Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md /// Note: The ERC-165 identifier for this interface is 0xd9b67a26. interface IERC1155 { /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. /// Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event /// from `0x0` to `0x0`, with the token creator as `_operator`. event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); /// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, /// including zero value transfers as well as minting or burning. ///Operator will always be msg.sender. /// Either event from address `0x0` signifies a minting operation. /// An event to address `0x0` signifies a burning or melting operation. /// The total value transferred from address 0x0 minus the total value transferred to 0x0 may /// be used by clients and exchanges to be added to the "circulating supply" for a given token ID. /// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event /// from `0x0` to `0x0`, with the token creator as `_operator`. event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /// @dev MUST emit when an approval is updated. event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /// @dev MUST emit when the URI is updated for a token ID. /// URIs are defined in RFC 3986. /// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema". event URI( string value, uint256 indexed id ); /// @notice Transfers value amount of an _id from the _from address to the _to address specified. /// @dev MUST emit TransferSingle event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if balance of sender for token `_id` is lower than the `_value` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155Received` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. /// @param from Source address /// @param to Target address /// @param id ID of the token type /// @param value Transfer amount /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address from, address to, uint256 id, uint256 value, bytes calldata data ) external; /// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). /// @dev MUST emit TransferBatch event on success. /// Caller must be approved to manage the _from account's tokens (see isApprovedForAll). /// MUST throw if `_to` is the zero address. /// MUST throw if length of `_ids` is not the same as length of `_values`. /// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent. /// MUST throw on any other error. /// When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). /// If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value /// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. /// @param from Source addresses /// @param to Target addresses /// @param ids IDs of each token type /// @param values Transfer amounts per token type /// @param data Additional data with no specified format, sent in call to `_to` function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; /// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. /// @dev MUST emit the ApprovalForAll event on success. /// @param operator Address to add to the set of authorized operators /// @param approved True if the operator is approved, false to revoke approval function setApprovalForAll(address operator, bool approved) external; /// @notice Queries the approval status of an operator for a given owner. /// @param owner The owner of the Tokens /// @param operator Address of authorized operator /// @return True if the operator is approved, false if not function isApprovedForAll(address owner, address operator) external view returns (bool); /// @notice Get the balance of an account's Tokens. /// @param owner The address of the token holder /// @param id ID of the Token /// @return The _owner's balance of the Token type requested function balanceOf(address owner, uint256 id) external view returns (uint256); /// @notice Get the balance of multiple account/token pairs /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return The _owner's balance of the Token types requested function balanceOfBatch( address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } /* Copyright 2019 ZeroEx Intl. 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. */ library LibAssetDataTransferRichErrors { // bytes4(keccak256("UnsupportedAssetProxyError(bytes4)")) bytes4 internal constant UNSUPPORTED_ASSET_PROXY_ERROR_SELECTOR = 0x7996a271; // bytes4(keccak256("Erc721AmountMustEqualOneError(uint256)")) bytes4 internal constant ERC721_AMOUNT_MUST_EQUAL_ONE_ERROR_SELECTOR = 0xbaffa474; // solhint-disable func-name-mixedcase function UnsupportedAssetProxyError( bytes4 proxyId ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UNSUPPORTED_ASSET_PROXY_ERROR_SELECTOR, proxyId ); } function Erc721AmountMustEqualOneError( uint256 amount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ERC721_AMOUNT_MUST_EQUAL_ONE_ERROR_SELECTOR, amount ); } } library LibAssetDataTransfer { using LibBytes for bytes; using LibSafeMath for uint256; using LibAssetDataTransfer for bytes; /// @dev Transfers given amount of asset to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferFrom( bytes memory assetData, address from, address to, uint256 amount ) internal { if (amount == 0) { return; } bytes4 proxyId = assetData.readBytes4(0); if ( proxyId == IAssetData(address(0)).ERC20Token.selector || proxyId == IAssetData(address(0)).ERC20Bridge.selector ) { assetData.transferERC20Token( from, to, amount ); } else if (proxyId == IAssetData(address(0)).ERC721Token.selector) { assetData.transferERC721Token( from, to, amount ); } else if (proxyId == IAssetData(address(0)).ERC1155Assets.selector) { assetData.transferERC1155Assets( from, to, amount ); } else if (proxyId == IAssetData(address(0)).MultiAsset.selector) { assetData.transferMultiAsset( from, to, amount ); } else if (proxyId != IAssetData(address(0)).StaticCall.selector) { LibRichErrors.rrevert(LibAssetDataTransferRichErrors.UnsupportedAssetProxyError( proxyId )); } } ///@dev Transfer asset from sender to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferIn( bytes memory assetData, uint256 amount ) internal { assetData.transferFrom( msg.sender, address(this), amount ); } ///@dev Transfer asset from this contract to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of asset to transfer to sender. function transferOut( bytes memory assetData, uint256 amount ) internal { assetData.transferFrom( address(this), msg.sender, amount ); } /// @dev Decodes ERC20 or ERC20Bridge assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferERC20Token( bytes memory assetData, address from, address to, uint256 amount ) internal { address token = assetData.readAddress(16); // Transfer tokens. if (from == address(this)) { LibERC20Token.transfer( token, to, amount ); } else { LibERC20Token.transferFrom( token, from, to, amount ); } } /// @dev Decodes ERC721 assetData and transfers given amount to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferERC721Token( bytes memory assetData, address from, address to, uint256 amount ) internal { if (amount != 1) { LibRichErrors.rrevert(LibAssetDataTransferRichErrors.Erc721AmountMustEqualOneError( amount )); } // Decode asset data. address token = assetData.readAddress(16); uint256 tokenId = assetData.readUint256(36); // Perform transfer. IERC721Token(token).transferFrom( from, to, tokenId ); } /// @dev Decodes ERC1155 assetData and transfers given amounts to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferERC1155Assets( bytes memory assetData, address from, address to, uint256 amount ) internal { // Decode assetData // solhint-disable ( address token, uint256[] memory ids, uint256[] memory values, bytes memory data ) = abi.decode( assetData.slice(4, assetData.length), (address, uint256[], uint256[], bytes) ); // solhint-enable // Scale up values by `amount` uint256 length = values.length; uint256[] memory scaledValues = new uint256[](length); for (uint256 i = 0; i != length; i++) { scaledValues[i] = values[i].safeMul(amount); } // Execute `safeBatchTransferFrom` call // Either succeeds or throws IERC1155(token).safeBatchTransferFrom( from, to, ids, scaledValues, data ); } /// @dev Decodes MultiAsset assetData and recursively transfers assets to sender. /// @param assetData Byte array encoded for the respective asset proxy. /// @param from Address to transfer asset from. /// @param to Address to transfer asset to. /// @param amount Amount of asset to transfer to sender. function transferMultiAsset( bytes memory assetData, address from, address to, uint256 amount ) internal { // solhint-disable indent (uint256[] memory nestedAmounts, bytes[] memory nestedAssetData) = abi.decode( assetData.slice(4, assetData.length), (uint256[], bytes[]) ); // solhint-enable indent uint256 numNestedAssets = nestedAssetData.length; for (uint256 i = 0; i != numNestedAssets; i++) { transferFrom( nestedAssetData[i], from, to, amount.safeMul(nestedAmounts[i]) ); } } } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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 IEtherToken is IERC20Token { function deposit() public payable; function withdraw(uint256 amount) public; } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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. */ library LibFillResults { using LibSafeMath for uint256; struct BatchMatchedFillResults { FillResults[] left; // Fill results for left orders FillResults[] right; // Fill results for right orders uint256 profitInLeftMakerAsset; // Profit taken from left makers uint256 profitInRightMakerAsset; // Profit taken from right makers } struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s). uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract. } struct MatchedFillResults { FillResults left; // Amounts filled and fees paid of left order. FillResults right; // Amounts filled and fees paid of right order. uint256 profitInLeftMakerAsset; // Profit taken from the left maker uint256 profitInRightMakerAsset; // Profit taken from the right maker } /// @dev Calculates amounts filled and fees paid by maker and taker. /// @param order to be filled. /// @param takerAssetFilledAmount Amount of takerAsset that will be filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @return fillResults Amounts filled and fees paid by maker and taker. function calculateFillResults( LibOrder.Order memory order, uint256 takerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice ) internal pure returns (FillResults memory fillResults) { // Compute proportional transfer amounts fillResults.takerAssetFilledAmount = takerAssetFilledAmount; fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerAssetAmount ); fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerFee ); fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.takerFee ); // Compute the protocol fee that should be paid for a single fill. fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier); return fillResults; } /// @dev Calculates fill amounts for the matched orders. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the leftOrder order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftOrderTakerAssetFilledAmount Amount of left order already filled. /// @param rightOrderTakerAssetFilledAmount Amount of right order already filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use /// the maximal fill order matching strategy. /// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders. function calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftOrderTakerAssetFilledAmount, uint256 rightOrderTakerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice, bool shouldMaximallyFillOrders ) internal pure returns (MatchedFillResults memory matchedFillResults) { // Derive maker asset amounts for left & right orders, given store taker assert amounts uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount); uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, leftTakerAssetAmountRemaining ); uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount); uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, rightTakerAssetAmountRemaining ); // Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets. if (shouldMaximallyFillOrders) { matchedFillResults = _calculateMatchedFillResultsWithMaximalFill( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else { matchedFillResults = _calculateMatchedFillResults( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Compute fees for left order matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.makerAssetFilledAmount, leftOrder.makerAssetAmount, leftOrder.makerFee ); matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.takerAssetFilledAmount, leftOrder.takerAssetAmount, leftOrder.takerFee ); // Compute fees for right order matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.makerAssetFilledAmount, rightOrder.makerAssetAmount, rightOrder.makerFee ); matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.takerAssetFilledAmount, rightOrder.takerAssetAmount, rightOrder.takerFee ); // Compute the protocol fee that should be paid for a single fill. In this // case this should be made the protocol fee for both the left and right orders. uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier); matchedFillResults.left.protocolFeePaid = protocolFee; matchedFillResults.right.protocolFeePaid = protocolFee; // Return fill results return matchedFillResults; } /// @dev Adds properties of both FillResults instances. /// @param fillResults1 The first FillResults. /// @param fillResults2 The second FillResults. /// @return The sum of both fill results. function addFillResults( FillResults memory fillResults1, FillResults memory fillResults2 ) internal pure returns (FillResults memory totalFillResults) { totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount); totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount); totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid); totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid); totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid); return totalFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only /// awards profit denominated in the left maker asset. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate fill results for maker and taker assets: at least one order will be fully filled. // The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining` // The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining` // We have two distinct cases for calculating the fill results: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // If the left maker can buy exactly what the right maker can sell, then both orders are fully filled. // Case 2. // If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled. // Case 3. // If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) { // Case 2: Left order is fully filled matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round up to ensure the maker's exchange rate does not exceed the price specified by the order. // We favor the maker when the exchange rate must be rounded. matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil( rightOrder.takerAssetAmount, rightOrder.makerAssetAmount, leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount ); } else { // leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining // Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but // this calculation will be more precise since it does not include rounding. matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); return matchedFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching /// strategy. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResultsWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset. bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining; bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining; // Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled. // // The maximum that the left maker can possibly buy is the amount that the right order can sell. // The maximum that the right maker can possibly buy is the amount that the left order can sell. // // If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled, // the profit will be out in the right maker asset. // // There are three cases to consider: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // Case 2. // If the right maker can buy more than the left maker can sell, then only the right order is fully filled. // Case 3. // If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of // what the right maker can buy, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled with the profit paid in the left makerAsset matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) { // Case 2: Left order is fully filled with the profit paid in the right makerAsset. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round down to ensure the right maker's exchange rate does not exceed the price specified by the order. // We favor the right maker when the exchange rate must be rounded and the profit is being paid in the // right maker asset. matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, leftMakerAssetAmountRemaining ); matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining; } else { // Case 3: The right and left orders are fully filled matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit. if (doesLeftMakerAssetProfitExist) { matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); } // Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit. if (doesRightMakerAssetProfitExist) { matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub( matchedFillResults.left.takerAssetFilledAmount ); } return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. Both orders will be fully filled in this /// case. /// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled. /// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteFillBoth( uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate the fully filled results for both orders. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. /// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts /// can be derived from this order and the right asset remaining fields. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteRightFill( LibOrder.Order memory leftOrder, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining; // Round down to ensure the left maker's exchange rate does not exceed the price specified by the order. // We favor the left maker when the exchange rate must be rounded and the profit is being paid in the // left maker asset. matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, rightMakerAssetAmountRemaining ); return matchedFillResults; } } contract IExchangeCore { // Fill event is emitted whenever an order is filled. event Fill( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that received fees. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset. bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset. bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash). address takerAddress, // Address that filled the order. address senderAddress, // Address that called the Exchange contract (msg.sender). uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker. uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker. uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker. uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker. uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract. ); // Cancel event is emitted whenever an individual order is cancelled. event Cancel( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. address senderAddress, // Address that called the Exchange contract (msg.sender). bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash). ); // CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully. event CancelUpTo( address indexed makerAddress, // Orders cancelled must have been created by this address. address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address. uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled. ); /// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch /// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress). /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. function cancelOrdersUpTo(uint256 targetOrderEpoch) external payable; /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev After calling, the order can not be filled anymore. /// @param order Order struct containing order specifications. function cancelOrder(LibOrder.Order memory order) public payable; /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(LibOrder.Order memory order) public view returns (LibOrder.OrderInfo memory orderInfo); } /* Copyright 2019 ZeroEx Intl. 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 IProtocolFees { // Logs updates to the protocol fee multiplier. event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier); // Logs updates to the protocolFeeCollector address. event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector); /// @dev Allows the owner to update the protocol fee multiplier. /// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier. function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier) external; /// @dev Allows the owner to update the protocolFeeCollector address. /// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address. function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector) external; /// @dev Returns the protocolFeeMultiplier function protocolFeeMultiplier() external view returns (uint256); /// @dev Returns the protocolFeeCollector address function protocolFeeCollector() external view returns (address); } /* Copyright 2019 ZeroEx Intl. 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 IMatchOrders { /// @dev Match complementary orders that have a profitable spread. /// Each order is filled at their respective price point, and /// the matcher receives a profit denominated in the left maker asset. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrders( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrdersWithMaximalFill( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the left order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled by maker and taker of matched orders. function matchOrdersWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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. */ library LibZeroExTransaction { using LibZeroExTransaction for ZeroExTransaction; // Hash for the EIP712 0x transaction schema // keccak256(abi.encodePacked( // "ZeroExTransaction(", // "uint256 salt,", // "uint256 expirationTimeSeconds,", // "uint256 gasPrice,", // "address signerAddress,", // "bytes data", // ")" // )); bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508; struct ZeroExTransaction { uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash. uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires. uint256 gasPrice; // gasPrice that transaction is required to be executed with. address signerAddress; // Address of transaction signer. bytes data; // AbiV2 encoded calldata. } /// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator. /// @param transaction 0x transaction structure. /// @return EIP712 typed data hash of the transaction. function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 transactionHash) { // Hash the transaction with the domain separator of the Exchange contract. transactionHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, transaction.getStructHash() ); return transactionHash; } /// @dev Calculates EIP712 hash of the 0x transaction struct. /// @param transaction 0x transaction structure. /// @return EIP712 hash of the transaction struct. function getStructHash(ZeroExTransaction memory transaction) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH; bytes memory data = transaction.data; uint256 salt = transaction.salt; uint256 expirationTimeSeconds = transaction.expirationTimeSeconds; uint256 gasPrice = transaction.gasPrice; address signerAddress = transaction.signerAddress; // Assembly for more efficiently computing: // result = keccak256(abi.encodePacked( // schemaHash, // salt, // expirationTimeSeconds, // gasPrice, // uint256(signerAddress), // keccak256(data) // )); assembly { // Compute hash of data let dataHash := keccak256(add(data, 32), mload(data)) // Load free memory pointer let memPtr := mload(64) mstore(memPtr, schemaHash) // hash of schema mstore(add(memPtr, 32), salt) // salt mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds mstore(add(memPtr, 96), gasPrice) // gasPrice mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress mstore(add(memPtr, 160), dataHash) // hash of data // Compute hash result := keccak256(memPtr, 192) } return result; } } contract ISignatureValidator { // Allowed signature types. enum SignatureType { Illegal, // 0x00, default value Invalid, // 0x01 EIP712, // 0x02 EthSign, // 0x03 Wallet, // 0x04 Validator, // 0x05 PreSigned, // 0x06 EIP1271Wallet, // 0x07 NSignatureTypes // 0x08, number of signature types. Always leave at end. } event SignatureValidatorApproval( address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures. address indexed validatorAddress, // Address of signature validator contract. bool isApproved // Approval or disapproval of validator contract. ); /// @dev Approves a hash on-chain. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param hash Any 32-byte hash. function preSign(bytes32 hash) external payable; /// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf. /// @param validatorAddress Address of Validator contract. /// @param approval Approval or disapproval of Validator contract. function setSignatureValidatorApproval( address validatorAddress, bool approval ) external payable; /// @dev Verifies that a hash has been signed by the given signer. /// @param hash Any 32-byte hash. /// @param signature Proof that the hash has been signed by signer. /// @return isValid `true` if the signature is valid for the given hash and signer. function isValidHashSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for an order is valid. /// @param order The order. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given order and signer. function isValidOrderSignature( LibOrder.Order memory order, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for a transaction is valid. /// @param transaction The transaction. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given transaction and signer. function isValidTransactionSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that an order, with provided order hash, has been signed /// by the given signer. /// @param order The order. /// @param orderHash The hash of the order. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given order and signer. function _isValidOrderWithHashSignature( LibOrder.Order memory order, bytes32 orderHash, bytes memory signature ) internal view returns (bool isValid); /// @dev Verifies that a transaction, with provided order hash, has been signed /// by the given signer. /// @param transaction The transaction. /// @param transactionHash The hash of the transaction. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given transaction and signer. function _isValidTransactionWithHashSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes32 transactionHash, bytes memory signature ) internal view returns (bool isValid); } /* Copyright 2019 ZeroEx Intl. 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 ITransactions { // TransactionExecution event is emitted when a ZeroExTransaction is executed. event TransactionExecution(bytes32 indexed transactionHash); /// @dev Executes an Exchange method call in the context of signer. /// @param transaction 0x transaction containing salt, signerAddress, and data. /// @param signature Proof that transaction has been signed by signer. /// @return ABI encoded return data of the underlying Exchange function call. function executeTransaction( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public payable returns (bytes memory); /// @dev Executes a batch of Exchange method calls in the context of signer(s). /// @param transactions Array of 0x transactions containing salt, signerAddress, and data. /// @param signatures Array of proofs that transactions have been signed by signer(s). /// @return Array containing ABI encoded return data for each of the underlying Exchange function calls. function batchExecuteTransactions( LibZeroExTransaction.ZeroExTransaction[] memory transactions, bytes[] memory signatures ) public payable returns (bytes[] memory); /// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`). /// If calling a fill function, this address will represent the taker. /// If calling a cancel function, this address will represent the maker. /// @return Signer of 0x transaction if entry point is `executeTransaction`. /// `msg.sender` if entry point is any other function. function _getCurrentContextAddress() internal view returns (address); } /* Copyright 2019 ZeroEx Intl. 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 IAssetProxyDispatcher { // Logs registration of new asset proxy event AssetProxyRegistered( bytes4 id, // Id of new registered AssetProxy. address assetProxy // Address of new registered AssetProxy. ); /// @dev Registers an asset proxy to its asset proxy id. /// Once an asset proxy is registered, it cannot be unregistered. /// @param assetProxy Address of new asset proxy to register. function registerAssetProxy(address assetProxy) external; /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. function getAssetProxy(bytes4 assetProxyId) external view returns (address); } /* Copyright 2019 ZeroEx Intl. 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 IWrapperFunctions { /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. function fillOrKillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrKillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrKillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrdersNoThrow( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersNoThrow( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersNoThrow( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Minimum amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Minimum amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of cancelOrder. /// @param orders Array of order specifications. function batchCancelOrders(LibOrder.Order[] memory orders) public payable; } /* Copyright 2019 ZeroEx Intl. 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 ITransferSimulator { /// @dev This function may be used to simulate any amount of transfers /// As they would occur through the Exchange contract. Note that this function /// will always revert, even if all transfers are successful. However, it may /// be used with eth_call or with a try/catch pattern in order to simulate /// the results of the transfers. /// @param assetData Array of asset details, each encoded per the AssetProxy contract specification. /// @param fromAddresses Array containing the `from` addresses that correspond with each transfer. /// @param toAddresses Array containing the `to` addresses that correspond with each transfer. /// @param amounts Array containing the amounts that correspond to each transfer. /// @return This function does not return a value. However, it will always revert with /// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful. function simulateDispatchTransferFromCalls( bytes[] memory assetData, address[] memory fromAddresses, address[] memory toAddresses, uint256[] memory amounts ) public; } // solhint-disable no-empty-blocks contract IExchange is IProtocolFees, IExchangeCore, IMatchOrders, ISignatureValidator, ITransactions, IAssetProxyDispatcher, ITransferSimulator, IWrapperFunctions {} /* Copyright 2019 ZeroEx Intl. 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. */ library LibWethUtilsRichErrors { // bytes4(keccak256("UnregisteredAssetProxyError()")) bytes4 internal constant UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR = 0xf3b96b8d; // bytes4(keccak256("InsufficientEthForFeeError(uint256,uint256)")) bytes4 internal constant INSUFFICIENT_ETH_FOR_FEE_ERROR_SELECTOR = 0xecf40fd9; // bytes4(keccak256("DefaultFunctionWethContractOnlyError(address)")) bytes4 internal constant DEFAULT_FUNCTION_WETH_CONTRACT_ONLY_ERROR_SELECTOR = 0x08b18698; // bytes4(keccak256("EthFeeLengthMismatchError(uint256,uint256)")) bytes4 internal constant ETH_FEE_LENGTH_MISMATCH_ERROR_SELECTOR = 0x3ecb6ceb; // solhint-disable func-name-mixedcase function UnregisteredAssetProxyError() internal pure returns (bytes memory) { return abi.encodeWithSelector(UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR); } function InsufficientEthForFeeError( uint256 ethFeeRequired, uint256 ethAvailable ) internal pure returns (bytes memory) { return abi.encodeWithSelector( INSUFFICIENT_ETH_FOR_FEE_ERROR_SELECTOR, ethFeeRequired, ethAvailable ); } function DefaultFunctionWethContractOnlyError( address senderAddress ) internal pure returns (bytes memory) { return abi.encodeWithSelector( DEFAULT_FUNCTION_WETH_CONTRACT_ONLY_ERROR_SELECTOR, senderAddress ); } function EthFeeLengthMismatchError( uint256 ethFeesLength, uint256 feeRecipientsLength ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ETH_FEE_LENGTH_MISMATCH_ERROR_SELECTOR, ethFeesLength, feeRecipientsLength ); } } contract MixinWethUtils { uint256 constant internal MAX_UINT256 = uint256(-1); // solhint-disable var-name-mixedcase IEtherToken internal WETH; bytes internal WETH_ASSET_DATA; // solhint-enable var-name-mixedcase using LibSafeMath for uint256; constructor ( address exchange, address weth ) public { WETH = IEtherToken(weth); WETH_ASSET_DATA = abi.encodeWithSelector( IAssetData(address(0)).ERC20Token.selector, weth ); address proxyAddress = IExchange(exchange).getAssetProxy(IAssetData(address(0)).ERC20Token.selector); if (proxyAddress == address(0)) { LibRichErrors.rrevert(LibWethUtilsRichErrors.UnregisteredAssetProxyError()); } WETH.approve(proxyAddress, MAX_UINT256); address protocolFeeCollector = IExchange(exchange).protocolFeeCollector(); if (protocolFeeCollector != address(0)) { WETH.approve(protocolFeeCollector, MAX_UINT256); } } /// @dev Default payable function, this allows us to withdraw WETH function () external payable { if (msg.sender != address(WETH)) { LibRichErrors.rrevert(LibWethUtilsRichErrors.DefaultFunctionWethContractOnlyError( msg.sender )); } } /// @dev Transfers ETH denominated fees to all feeRecipient addresses /// @param ethFeeAmounts Amounts of ETH, denominated in Wei, that are paid to corresponding feeRecipients. /// @param feeRecipients Addresses that will receive ETH when orders are filled. /// @return ethRemaining msg.value minus the amount of ETH spent on affiliate fees. function _transferEthFeesAndWrapRemaining( uint256[] memory ethFeeAmounts, address payable[] memory feeRecipients ) internal returns (uint256 ethRemaining) { uint256 feesLen = ethFeeAmounts.length; // ethFeeAmounts len must equal feeRecipients len if (feesLen != feeRecipients.length) { LibRichErrors.rrevert(LibWethUtilsRichErrors.EthFeeLengthMismatchError( feesLen, feeRecipients.length )); } // This function is always called before any other function, so we assume that // the ETH remaining is the entire msg.value. ethRemaining = msg.value; for (uint256 i = 0; i != feesLen; i++) { uint256 ethFeeAmount = ethFeeAmounts[i]; // Ensure there is enough ETH to pay the fee if (ethRemaining < ethFeeAmount) { LibRichErrors.rrevert(LibWethUtilsRichErrors.InsufficientEthForFeeError( ethFeeAmount, ethRemaining )); } // Decrease ethRemaining and transfer fee to corresponding feeRecipient ethRemaining = ethRemaining.safeSub(ethFeeAmount); feeRecipients[i].transfer(ethFeeAmount); } // Convert remaining ETH to WETH. WETH.deposit.value(ethRemaining)(); return ethRemaining; } /// @dev Unwraps WETH and transfers ETH to msg.sender. /// @param transferAmount Amount of WETH balance to unwrap and transfer. function _unwrapAndTransferEth( uint256 transferAmount ) internal { // Do nothing if amount is zero if (transferAmount > 0) { // Convert WETH to ETH WETH.withdraw(transferAmount); // Transfer ETH to sender msg.sender.transfer(transferAmount); } } /// @dev transfers ETH to address. /// @param transferAmount Amount of eth to transfer. function _transferEthToAddress( uint256 transferAmount, address transferAddress ) internal { // Do nothing if amount is zero if (transferAmount > 0) { address payable transferAddresspayable = address(uint160(transferAddress)); transferAddresspayable.transfer(transferAmount); } } } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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 IOwnable { /// @dev Emitted by Ownable when ownership is transferred. /// @param previousOwner The previous owner of the contract. /// @param newOwner The new owner of the contract. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @dev Transfers ownership of the contract to a new address. /// @param newOwner The address that will become the owner. function transferOwnership(address newOwner) public; } library LibOwnableRichErrors { // bytes4(keccak256("OnlyOwnerError(address,address)")) bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR = 0x1de45ad1; // bytes4(keccak256("TransferOwnerToZeroError()")) bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES = hex"e69edc3e"; // solhint-disable func-name-mixedcase function OnlyOwnerError( address sender, address owner ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ONLY_OWNER_ERROR_SELECTOR, sender, owner ); } function TransferOwnerToZeroError() internal pure returns (bytes memory) { return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES; } } contract Ownable is IOwnable { /// @dev The owner of this contract. /// @return 0 The owner address. address public owner; constructor () public { owner = msg.sender; } modifier onlyOwner() { _assertSenderIsOwner(); _; } /// @dev Change the owner of this contract. /// @param newOwner New owner address. function transferOwnership(address newOwner) public onlyOwner { if (newOwner == address(0)) { LibRichErrors.rrevert(LibOwnableRichErrors.TransferOwnerToZeroError()); } else { owner = newOwner; emit OwnershipTransferred(msg.sender, newOwner); } } function _assertSenderIsOwner() internal view { if (msg.sender != owner) { LibRichErrors.rrevert(LibOwnableRichErrors.OnlyOwnerError( msg.sender, owner )); } } } /* Copyright 2019 ZeroEx Intl. 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. */ library LibForwarderRichErrors { // bytes4(keccak256("UnregisteredAssetProxyError()")) bytes4 internal constant UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR = 0xf3b96b8d; // bytes4(keccak256("CompleteBuyFailedError(uint256,uint256)")) bytes4 internal constant COMPLETE_BUY_FAILED_ERROR_SELECTOR = 0x91353a0c; // bytes4(keccak256("CompleteSellFailedError(uint256,uint256)")) bytes4 internal constant COMPLETE_SELL_FAILED_ERROR_SELECTOR = 0x450a0219; // bytes4(keccak256("UnsupportedFeeError(bytes)")) bytes4 internal constant UNSUPPORTED_FEE_ERROR_SELECTOR = 0x31360af1; // bytes4(keccak256("OverspentWethError(uint256,uint256)")) bytes4 internal constant OVERSPENT_WETH_ERROR_SELECTOR = 0xcdcbed5d; // solhint-disable func-name-mixedcase function UnregisteredAssetProxyError() internal pure returns (bytes memory) { return abi.encodeWithSelector(UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR); } function CompleteBuyFailedError( uint256 expectedAssetBuyAmount, uint256 actualAssetBuyAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( COMPLETE_BUY_FAILED_ERROR_SELECTOR, expectedAssetBuyAmount, actualAssetBuyAmount ); } function CompleteSellFailedError( uint256 expectedAssetSellAmount, uint256 actualAssetSellAmount ) internal pure returns (bytes memory) { return abi.encodeWithSelector( COMPLETE_SELL_FAILED_ERROR_SELECTOR, expectedAssetSellAmount, actualAssetSellAmount ); } function UnsupportedFeeError( bytes memory takerFeeAssetData ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UNSUPPORTED_FEE_ERROR_SELECTOR, takerFeeAssetData ); } function OverspentWethError( uint256 wethSpent, uint256 msgValue ) internal pure returns (bytes memory) { return abi.encodeWithSelector( OVERSPENT_WETH_ERROR_SELECTOR, wethSpent, msgValue ); } } /* Copyright 2019 ZeroEx Intl. 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. */ /* Copyright 2019 ZeroEx Intl. 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 IExchangeV2 { // solhint-disable max-line-length struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted. uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy. } // solhint-enable max-line-length struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s). } struct OrderInfo { uint8 orderStatus; // Status that describes order's validity and fillability. bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash). uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled. } /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public returns (FillResults memory fillResults); /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(Order memory order) public returns (OrderInfo memory orderInfo); function executeTransaction( uint256 salt, address signerAddress, bytes calldata data, bytes calldata signature ) external; } contract MixinExchangeWrapper { // The v2 order id is the first 4 bytes of the ExchangeV2 order schema hash. // bytes4(keccak256(abi.encodePacked( // "Order(", // "address makerAddress,", // "address takerAddress,", // "address feeRecipientAddress,", // "address senderAddress,", // "uint256 makerAssetAmount,", // "uint256 takerAssetAmount,", // "uint256 makerFee,", // "uint256 takerFee,", // "uint256 expirationTimeSeconds,", // "uint256 salt,", // "bytes makerAssetData,", // "bytes takerAssetData", // ")" // ))); bytes4 constant public EXCHANGE_V2_ORDER_ID = 0x770501f8; bytes4 constant internal ERC20_BRIDGE_PROXY_ID = 0xdc1600f3; // solhint-disable var-name-mixedcase IExchange internal EXCHANGE; IExchangeV2 internal EXCHANGE_V2; // solhint-enable var-name-mixedcase using LibBytes for bytes; using LibAssetDataTransfer for bytes; using LibSafeMath for uint256; constructor ( address _exchange, address _exchangeV2 ) public { EXCHANGE = IExchange(_exchange); EXCHANGE_V2 = IExchangeV2(_exchangeV2); } struct SellFillResults { uint256 wethSpentAmount; uint256 makerAssetAcquiredAmount; uint256 protocolFeePaid; } /// @dev Fills the input order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function _fillOrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (LibFillResults.FillResults memory fillResults) { if (_isV2Order(order)) { return _fillV2OrderNoThrow( order, takerAssetFillAmount, signature ); } return _fillV3OrderNoThrow( order, takerAssetFillAmount, signature ); } /// @dev Executes a single call of fillOrder according to the wethSellAmount and /// the amount already sold. /// @param order A single order specification. /// @param signature Signature for the given order. /// @param remainingTakerAssetFillAmount Remaining amount of WETH to sell. /// @return wethSpentAmount Amount of WETH spent on the given order. /// @return makerAssetAcquiredAmount Amount of maker asset acquired from the given order. function _marketSellSingleOrder( LibOrder.Order memory order, bytes memory signature, uint256 remainingTakerAssetFillAmount ) internal returns (SellFillResults memory sellFillResults) { // If the maker asset is ERC20Bridge, take a snapshot of the Forwarder contract's balance. bytes4 makerAssetProxyId = order.makerAssetData.readBytes4(0); address tokenAddress; uint256 balanceBefore; if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) { tokenAddress = order.makerAssetData.readAddress(16); balanceBefore = IERC20Token(tokenAddress).balanceOf(address(this)); } // No taker fee or percentage fee if ( order.takerFee == 0 || _areUnderlyingAssetsEqual(order.takerFeeAssetData, order.makerAssetData) ) { // Attempt to sell the remaining amount of WETH LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow( order, remainingTakerAssetFillAmount, signature ); sellFillResults.wethSpentAmount = singleFillResults.takerAssetFilledAmount; sellFillResults.protocolFeePaid = singleFillResults.protocolFeePaid; // Subtract fee from makerAssetFilledAmount for the net amount acquired. sellFillResults.makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount .safeSub(singleFillResults.takerFeePaid); // WETH fee } else if (_areUnderlyingAssetsEqual(order.takerFeeAssetData, order.takerAssetData)) { // We will first sell WETH as the takerAsset, then use it to pay the takerFee. // This ensures that we reserve enough to pay the taker and protocol fees. uint256 takerAssetFillAmount = LibMath.getPartialAmountCeil( order.takerAssetAmount, order.takerAssetAmount.safeAdd(order.takerFee), remainingTakerAssetFillAmount ); LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow( order, takerAssetFillAmount, signature ); // WETH is also spent on the taker fee, so we add it here. sellFillResults.wethSpentAmount = singleFillResults.takerAssetFilledAmount .safeAdd(singleFillResults.takerFeePaid); sellFillResults.makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount; sellFillResults.protocolFeePaid = singleFillResults.protocolFeePaid; // Unsupported fee } else { LibRichErrors.rrevert(LibForwarderRichErrors.UnsupportedFeeError(order.takerFeeAssetData)); } // Account for the ERC20Bridge transfering more of the maker asset than expected. if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) { uint256 balanceAfter = IERC20Token(tokenAddress).balanceOf(address(this)); sellFillResults.makerAssetAcquiredAmount = LibSafeMath.max256( balanceAfter.safeSub(balanceBefore), sellFillResults.makerAssetAcquiredAmount ); } order.makerAssetData.transferOut(sellFillResults.makerAssetAcquiredAmount); return sellFillResults; } /// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH has been sold by taker. /// @param orders Array of order specifications. /// @param wethSellAmount Desired amount of WETH to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return totalWethSpentAmount Total amount of WETH spent on the given orders. /// @return totalMakerAssetAcquiredAmount Total amount of maker asset acquired from the given orders. function _marketSellNoThrow( LibOrder.Order[] memory orders, uint256 wethSellAmount, bytes[] memory signatures ) internal returns ( uint256 totalWethSpentAmount, uint256 totalMakerAssetAcquiredAmount ) { uint256 protocolFee = tx.gasprice.safeMul(EXCHANGE.protocolFeeMultiplier()); for (uint256 i = 0; i != orders.length; i++) { // Preemptively skip to avoid division by zero in _marketSellSingleOrder if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) { continue; } // The remaining amount of WETH to sell uint256 remainingTakerAssetFillAmount = wethSellAmount .safeSub(totalWethSpentAmount); uint256 currentProtocolFee = _isV2Order(orders[i]) ? 0 : protocolFee; if (remainingTakerAssetFillAmount > currentProtocolFee) { // Do not count the protocol fee as part of the fill amount. remainingTakerAssetFillAmount = remainingTakerAssetFillAmount.safeSub(currentProtocolFee); } else { // Stop if we don't have at least enough ETH to pay another protocol fee. break; } SellFillResults memory sellFillResults = _marketSellSingleOrder( orders[i], signatures[i], remainingTakerAssetFillAmount ); totalWethSpentAmount = totalWethSpentAmount .safeAdd(sellFillResults.wethSpentAmount) .safeAdd(sellFillResults.protocolFeePaid); totalMakerAssetAcquiredAmount = totalMakerAssetAcquiredAmount .safeAdd(sellFillResults.makerAssetAcquiredAmount); // Stop execution if the entire amount of WETH has been sold if (totalWethSpentAmount >= wethSellAmount) { break; } } } /// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH (exclusive of protocol fee) /// has been sold by taker. /// @param orders Array of order specifications. /// @param wethSellAmount Desired amount of WETH to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return totalWethSpentAmount Total amount of WETH spent on the given orders. /// @return totalMakerAssetAcquiredAmount Total amount of maker asset acquired from the given orders. function _marketSellExactAmountNoThrow( LibOrder.Order[] memory orders, uint256 wethSellAmount, bytes[] memory signatures ) internal returns ( uint256 totalWethSpentAmount, uint256 totalMakerAssetAcquiredAmount ) { uint256 totalProtocolFeePaid; for (uint256 i = 0; i != orders.length; i++) { // Preemptively skip to avoid division by zero in _marketSellSingleOrder if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) { continue; } // The remaining amount of WETH to sell uint256 remainingTakerAssetFillAmount = wethSellAmount .safeSub(totalWethSpentAmount); SellFillResults memory sellFillResults = _marketSellSingleOrder( orders[i], signatures[i], remainingTakerAssetFillAmount ); totalWethSpentAmount = totalWethSpentAmount .safeAdd(sellFillResults.wethSpentAmount); totalMakerAssetAcquiredAmount = totalMakerAssetAcquiredAmount .safeAdd(sellFillResults.makerAssetAcquiredAmount); totalProtocolFeePaid = totalProtocolFeePaid.safeAdd(sellFillResults.protocolFeePaid); // Stop execution if the entire amount of WETH has been sold if (totalWethSpentAmount >= wethSellAmount) { break; } } totalWethSpentAmount = totalWethSpentAmount.safeAdd(totalProtocolFeePaid); } /// @dev Executes a single call of fillOrder according to the makerAssetBuyAmount and /// the amount already bought. /// @param order A single order specification. /// @param signature Signature for the given order. /// @param remainingMakerAssetFillAmount Remaining amount of maker asset to buy. /// @return wethSpentAmount Amount of WETH spent on the given order. /// @return makerAssetAcquiredAmount Amount of maker asset acquired from the given order. function _marketBuySingleOrder( LibOrder.Order memory order, bytes memory signature, uint256 remainingMakerAssetFillAmount ) internal returns ( uint256 wethSpentAmount, uint256 makerAssetAcquiredAmount ) { // No taker fee or WETH fee if ( order.takerFee == 0 || _areUnderlyingAssetsEqual(order.takerFeeAssetData, order.takerAssetData) ) { // Calculate the remaining amount of takerAsset to sell uint256 remainingTakerAssetFillAmount = LibMath.getPartialAmountCeil( order.takerAssetAmount, order.makerAssetAmount, remainingMakerAssetFillAmount ); // Attempt to sell the remaining amount of takerAsset LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow( order, remainingTakerAssetFillAmount, signature ); // WETH is also spent on the protocol and taker fees, so we add it here. wethSpentAmount = singleFillResults.takerAssetFilledAmount .safeAdd(singleFillResults.takerFeePaid) .safeAdd(singleFillResults.protocolFeePaid); makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount; // Percentage fee } else if (_areUnderlyingAssetsEqual(order.takerFeeAssetData, order.makerAssetData)) { // Calculate the remaining amount of takerAsset to sell uint256 remainingTakerAssetFillAmount = LibMath.getPartialAmountCeil( order.takerAssetAmount, order.makerAssetAmount.safeSub(order.takerFee), remainingMakerAssetFillAmount ); // Attempt to sell the remaining amount of takerAsset LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow( order, remainingTakerAssetFillAmount, signature ); wethSpentAmount = singleFillResults.takerAssetFilledAmount .safeAdd(singleFillResults.protocolFeePaid); // Subtract fee from makerAssetFilledAmount for the net amount acquired. makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount .safeSub(singleFillResults.takerFeePaid); // Unsupported fee } else { LibRichErrors.rrevert(LibForwarderRichErrors.UnsupportedFeeError(order.takerFeeAssetData)); } return (wethSpentAmount, makerAssetAcquiredAmount); } /// @dev Synchronously executes multiple fill orders in a single transaction until total amount is acquired. /// Note that the Forwarder may fill more than the makerAssetBuyAmount so that, after percentage fees /// are paid, the net amount acquired after fees is equal to makerAssetBuyAmount (modulo rounding). /// The asset being sold by taker must always be WETH. /// @param orders Array of order specifications. /// @param makerAssetBuyAmount Desired amount of makerAsset to fill. /// @param signatures Proofs that orders have been signed by makers. /// @return totalWethSpentAmount Total amount of WETH spent on the given orders. /// @return totalMakerAssetAcquiredAmount Total amount of maker asset acquired from the given orders. function _marketBuyFillOrKill( LibOrder.Order[] memory orders, uint256 makerAssetBuyAmount, bytes[] memory signatures ) internal returns ( uint256 totalWethSpentAmount, uint256 totalMakerAssetAcquiredAmount ) { uint256 ordersLength = orders.length; for (uint256 i = 0; i != ordersLength; i++) { // Preemptively skip to avoid division by zero in _marketBuySingleOrder if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) { continue; } uint256 remainingMakerAssetFillAmount = makerAssetBuyAmount .safeSub(totalMakerAssetAcquiredAmount); // If the maker asset is ERC20Bridge, take a snapshot of the Forwarder contract's balance. bytes4 makerAssetProxyId = orders[i].makerAssetData.readBytes4(0); address tokenAddress; uint256 balanceBefore; if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) { tokenAddress = orders[i].makerAssetData.readAddress(16); balanceBefore = IERC20Token(tokenAddress).balanceOf(address(this)); } ( uint256 wethSpentAmount, uint256 makerAssetAcquiredAmount ) = _marketBuySingleOrder( orders[i], signatures[i], remainingMakerAssetFillAmount ); // Account for the ERC20Bridge transfering more of the maker asset than expected. if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) { uint256 balanceAfter = IERC20Token(tokenAddress).balanceOf(address(this)); makerAssetAcquiredAmount = LibSafeMath.max256( balanceAfter.safeSub(balanceBefore), makerAssetAcquiredAmount ); } orders[i].makerAssetData.transferOut(makerAssetAcquiredAmount); totalWethSpentAmount = totalWethSpentAmount .safeAdd(wethSpentAmount); totalMakerAssetAcquiredAmount = totalMakerAssetAcquiredAmount .safeAdd(makerAssetAcquiredAmount); // Stop execution if the entire amount of makerAsset has been bought if (totalMakerAssetAcquiredAmount >= makerAssetBuyAmount) { break; } } if (totalMakerAssetAcquiredAmount < makerAssetBuyAmount) { LibRichErrors.rrevert(LibForwarderRichErrors.CompleteBuyFailedError( makerAssetBuyAmount, totalMakerAssetAcquiredAmount )); } } /// @dev Fills the input ExchangeV2 order. The `makerFeeAssetData` must be // equal to EXCHANGE_V2_ORDER_ID (0x770501f8). /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function _fillV2OrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (LibFillResults.FillResults memory fillResults) { // Strip v3 specific fields from order IExchangeV2.Order memory v2Order = IExchangeV2.Order({ makerAddress: order.makerAddress, takerAddress: order.takerAddress, feeRecipientAddress: order.feeRecipientAddress, senderAddress: order.senderAddress, makerAssetAmount: order.makerAssetAmount, takerAssetAmount: order.takerAssetAmount, // NOTE: We assume fees are 0 for all v2 orders. Orders with non-zero fees will fail to be filled. makerFee: 0, takerFee: 0, expirationTimeSeconds: order.expirationTimeSeconds, salt: order.salt, makerAssetData: order.makerAssetData, takerAssetData: order.takerAssetData }); // ABI encode calldata for `fillOrder` bytes memory fillOrderCalldata = abi.encodeWithSelector( IExchangeV2(address(0)).fillOrder.selector, v2Order, takerAssetFillAmount, signature ); address exchange = address(EXCHANGE_V2); (bool didSucceed, bytes memory returnData) = exchange.call(fillOrderCalldata); if (didSucceed) { assert(returnData.length == 128); // NOTE: makerFeePaid, takerFeePaid, and protocolFeePaid will always be 0 for v2 orders (fillResults.makerAssetFilledAmount, fillResults.takerAssetFilledAmount) = abi.decode(returnData, (uint256, uint256)); } // fillResults values will be 0 by default if call was unsuccessful return fillResults; } /// @dev Fills the input ExchangeV3 order. /// Returns false if the transaction would otherwise revert. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function _fillV3OrderNoThrow( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) internal returns (LibFillResults.FillResults memory fillResults) { // ABI encode calldata for `fillOrder` bytes memory fillOrderCalldata = abi.encodeWithSelector( IExchange(address(0)).fillOrder.selector, order, takerAssetFillAmount, signature ); address exchange = address(EXCHANGE); (bool didSucceed, bytes memory returnData) = exchange.call(fillOrderCalldata); if (didSucceed) { assert(returnData.length == 160); fillResults = abi.decode(returnData, (LibFillResults.FillResults)); } // fillResults values will be 0 by default if call was unsuccessful return fillResults; } /// @dev Checks whether one asset is effectively equal to another asset. /// This is the case if they have the same ERC20Proxy/ERC20BridgeProxy asset data, or if /// one is the ERC20Bridge equivalent of the other. /// @param assetData1 Byte array encoded for the takerFee asset proxy. /// @param assetData2 Byte array encoded for the maker asset proxy. /// @return areEqual Whether or not the underlying assets are equal. function _areUnderlyingAssetsEqual( bytes memory assetData1, bytes memory assetData2 ) internal pure returns (bool) { bytes4 assetProxyId1 = assetData1.readBytes4(0); bytes4 assetProxyId2 = assetData2.readBytes4(0); bytes4 erc20ProxyId = IAssetData(address(0)).ERC20Token.selector; bytes4 erc20BridgeProxyId = IAssetData(address(0)).ERC20Bridge.selector; if ( (assetProxyId1 == erc20ProxyId || assetProxyId1 == erc20BridgeProxyId) && (assetProxyId2 == erc20ProxyId || assetProxyId2 == erc20BridgeProxyId) ) { // Compare the underlying token addresses. address token1 = assetData1.readAddress(16); address token2 = assetData2.readAddress(16); return (token1 == token2); } else { return assetData1.equals(assetData2); } } /// @dev Checks whether an order is a v2 order. /// @param order Order struct containing order specifications. /// @return True if the order's `makerFeeAssetData` is set to the v2 order id. function _isV2Order(LibOrder.Order memory order) internal pure returns (bool) { return order.makerFeeAssetData.length > 3 && order.makerFeeAssetData.readBytes4(0) == EXCHANGE_V2_ORDER_ID; } } /* Copyright 2019 ZeroEx Intl. 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 MixinReceiver { bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61; bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81; /// @notice Handle the receipt of a single ERC1155 token type /// @dev The smart contract calls this function on the recipient /// after a `safeTransferFrom`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the ///transaction being reverted /// Note: the contract address is always the message sender /// @param operator The address which called `safeTransferFrom` function /// @param from The address which previously owned the token /// @param id An array containing the ids of the token being transferred /// @param value An array containing the amount of tokens being transferred /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4) { return ERC1155_RECEIVED; } /// @notice Handle the receipt of multiple ERC1155 token types /// @dev The smart contract calls this function on the recipient /// after a `safeTransferFrom`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted /// Note: the contract address is always the message sender /// @param operator The address which called `safeTransferFrom` function /// @param from The address which previously owned the token /// @param ids An array containing ids of each token being transferred /// @param values An array containing amounts of each token being transferred /// @param data Additional data with no specified format /// @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4) { return ERC1155_BATCH_RECEIVED; } } /* Copyright 2019 ZeroEx Intl. 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 IForwarder { /// @dev Withdraws assets from this contract. The contract requires a ZRX balance in order to /// function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be /// used to withdraw assets that were accidentally sent to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of ERC20 token to withdraw. function withdrawAsset( bytes calldata assetData, uint256 amount ) external; } contract Forwarder is IForwarder, Ownable, MixinWethUtils, MixinExchangeWrapper, MixinReceiver { using LibBytes for bytes; using LibAssetDataTransfer for bytes; using LibSafeMath for uint256; constructor ( address _exchange, address _exchangeV2, address _weth ) public Ownable() MixinWethUtils( _exchange, _weth ) MixinExchangeWrapper( _exchange, _exchangeV2 ) {} // solhint-disable-line no-empty-blocks /// @dev Withdraws assets from this contract. It may be used by the owner to withdraw assets /// that were accidentally sent to this contract. /// @param assetData Byte array encoded for the respective asset proxy. /// @param amount Amount of the asset to withdraw. function withdrawAsset( bytes calldata assetData, uint256 amount ) external onlyOwner { assetData.transferOut(amount); } function executeTransactionv2(uint256 salt, address signerAddress, bytes memory data, bytes memory signature) public { if (data.readBytes4(0)==0xd46b02c3){ EXCHANGE_V2.executeTransaction(salt,signerAddress,data,signature); } } // maker lists NFT for x eth with this contract address as sender's address // the 0x order is only fillable via this sender's contract // contract then converts the weth to eth and sends to maker after taking the fees and royalty event Referred (address indexed refRecipient ,uint256 indexed refEthFeeAmount, uint256 platformfee); event Royalty (address indexed royaltyaddress ,uint256 indexed royaltyamt ); function BuyOrderWithEth( LibOrder.Order memory order, uint256 makerAssetBuyAmount, bytes memory signature, uint256 refEthFeeAmount, address payable refRecipient ) public payable returns ( uint256 orderwethSpentAmount, uint256 makerAssetAcquiredAmount ) { WETH.deposit.value(msg.value)(); require (order.makerAssetData.length == 132,"wrongdatatype"); require (order.takerAssetData.length == 68,"wrongdatatype"); uint256 royaltyamt = order.makerAssetData.readUint256(68); address royaltyaddress = order.makerAssetData.readAddress(112); uint256 platformfee = order.takerAssetData.readUint256(36); // converting to arrays for use in function LibOrder.Order[] memory orderarray = new LibOrder.Order[](1); orderarray[0] = order; bytes[] memory signaturearray = new bytes[](1); signaturearray[0] = signature; ( orderwethSpentAmount, makerAssetAcquiredAmount ) = _marketBuyFillOrKill( orderarray, makerAssetBuyAmount, signaturearray ); // Ensure that no extra WETH owned by this contract has been spent. require(msg.value >=orderwethSpentAmount + platformfee + royaltyamt ,'underpaid'); uint256 remaingEthAmount = msg.value.safeSub(orderwethSpentAmount); WETH.withdraw(remaingEthAmount); if (royaltyamt>0){ _transferEthToAddress(royaltyamt,royaltyaddress); } if (refEthFeeAmount>0){ require(refEthFeeAmount < platformfee.safeMul(26).safeDiv(100),'max referal exceeded'); _transferEthToAddress(refEthFeeAmount,refRecipient); _transferEthToAddress(platformfee.safeSub(refEthFeeAmount),owner); }else{ _transferEthToAddress(platformfee,owner); } uint256 wethRemaining = remaingEthAmount.safeSub(platformfee).safeSub(royaltyamt); //dust if (wethRemaining>10000000000000){ msg.sender.transfer(wethRemaining); } emit Referred (refRecipient , refEthFeeAmount ,platformfee); emit Royalty (royaltyaddress , royaltyamt); } }
converting to arrays for use in function Ensure that no extra WETH owned by this contract has been spent.dust
function BuyOrderWithEth( LibOrder.Order memory order, uint256 makerAssetBuyAmount, bytes memory signature, uint256 refEthFeeAmount, address payable refRecipient ) public payable returns ( uint256 orderwethSpentAmount, uint256 makerAssetAcquiredAmount ) { WETH.deposit.value(msg.value)(); require (order.makerAssetData.length == 132,"wrongdatatype"); require (order.takerAssetData.length == 68,"wrongdatatype"); uint256 royaltyamt = order.makerAssetData.readUint256(68); address royaltyaddress = order.makerAssetData.readAddress(112); uint256 platformfee = order.takerAssetData.readUint256(36); LibOrder.Order[] memory orderarray = new LibOrder.Order[](1); orderarray[0] = order; bytes[] memory signaturearray = new bytes[](1); signaturearray[0] = signature; ( orderwethSpentAmount, makerAssetAcquiredAmount ) = _marketBuyFillOrKill( orderarray, makerAssetBuyAmount, signaturearray ); require(msg.value >=orderwethSpentAmount + platformfee + royaltyamt ,'underpaid'); uint256 remaingEthAmount = msg.value.safeSub(orderwethSpentAmount); WETH.withdraw(remaingEthAmount); if (royaltyamt>0){ _transferEthToAddress(royaltyamt,royaltyaddress); } if (refEthFeeAmount>0){ require(refEthFeeAmount < platformfee.safeMul(26).safeDiv(100),'max referal exceeded'); _transferEthToAddress(refEthFeeAmount,refRecipient); _transferEthToAddress(platformfee.safeSub(refEthFeeAmount),owner); _transferEthToAddress(platformfee,owner); } uint256 wethRemaining = remaingEthAmount.safeSub(platformfee).safeSub(royaltyamt); if (wethRemaining>10000000000000){ msg.sender.transfer(wethRemaining); } emit Referred (refRecipient , refEthFeeAmount ,platformfee); emit Royalty (royaltyaddress , royaltyamt); }
2,221,092
./partial_match/56/0x5d237401f94B0E5F8191f155aD9f60970dd8dBB2/sources/CLOCKStake.sol
------------------------------------------------------------------------ Get the CLOCK balance of the token holder user the address of the token holder ------------------------------------------------------------------------
function yourCLOCKBalance(address user) external view returns(uint256 CLOCKBalance){ require(user != address(0), "ERC20: sending to the zero address"); return IERC20(CLOCK).balanceOf(user); }
11,164,236
./full_match/43113/0xF3c88f08927e321097BC85Ccfd685E56FF2dd0D1/sources/nft.sol
Calculate pricing Return prices index multiply with factor./
function getPrice() public view returns (uint256) { uint256 supply = totalSupply(); uint256 length = _prices.length - 1; uint256 square = SafeMath.mul(_row, _column); uint256 index = SafeMath.div(supply, square); if(price.status == true){ return price.value; return SafeMath.mul(_prices[length], PIXEL_PRICE_FACTOR); return SafeMath.mul(_prices[index], PIXEL_PRICE_FACTOR); } }
7,180,645
pragma solidity 0.5.9; /** * https://rekt.fyi * * Mock the performance of your friend's ETH stack by sending them a REKT token, and add a bounty to it. * * REKT tokens are non-transferrable. Holders can only burn the token and collect the bounty once their * ETH balance is m times higher or their ETH is worth m times more in USD than when they received the * token, where m is a multiplier value set by users. * * copyright 2019 rekt.fyi * * 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/>. */ /** * Libraries */ /// 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/>. library DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } 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; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } 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); } } } } /** * External Contracts */ contract Medianizer { function peek() public view returns (bytes32, bool) {} } contract Dai { function transferFrom(address src, address dst, uint wad) public returns (bool) {} } /** * Contracts */ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title https://rekt.fyi * @notice Mock the performance of your friend's ETH stack by sending them a REKT token, and add a bounty to it. * * REKT tokens are non-transferrable. Holders can only burn the token and collect the bounty once their * ETH balance is m times higher or their ETH is worth m times more in USD than when they received the * token, where m is a multiplier value set by users. */ contract RektFyi is Ownable { using DSMath for uint; /** * Storage */ struct Receiver { uint walletBalance; uint bountyETH; uint bountyDAI; uint timestamp; uint etherPrice; address payable sender; } struct Vault { uint fee; uint bountyETH; uint bountySAI; // DAI bounty sent here before the switch to MCD uint bountyDAI; // DAI bounty sent here after the switch to MCD } struct Pot { uint ETH; uint DAI; } mapping(address => Receiver) public receiver; mapping(address => uint) public balance; mapping(address => address[]) private recipients; mapping(address => Pot) public unredeemedBounty; mapping(address => Vault) public vault; Pot public bountyPot = Pot(0,0); uint public feePot = 0; bool public shutdown = false; uint public totalSupply = 0; uint public multiplier = 1300000000000000000; // 1.3x to start uint public bumpBasePrice = 10000000000000000; // 0.01 ETH uint public holdTimeCeiling = 3628800; // 6 weeks in seconds address public medianizerAddress; Medianizer oracle; bool public isMCD = false; uint public MCDswitchTimestamp = 0; address public saiAddress; address public daiAddress; Dai dai; Dai sai; constructor(address _medianizerAddress, address _saiAddress) public { medianizerAddress = _medianizerAddress; oracle = Medianizer(medianizerAddress); saiAddress = _saiAddress; dai = Dai(saiAddress); sai = dai; } /** * Constants */ string public constant name = "REKT.fyi"; string public constant symbol = "REKT"; uint8 public constant decimals = 0; uint public constant WAD = 1000000000000000000; uint public constant PRECISION = 100000000000000; // 4 orders of magnitude / decimal places uint public constant MULTIPLIER_FLOOR = 1000000000000000000; // 1x uint public constant MULTIPLIER_CEILING = 10000000000000000000; // 10x uint public constant BONUS_FLOOR = 1250000000000000000; //1.25x uint public constant BONUS_CEILING = 1800000000000000000; //1.8x uint public constant BOUNTY_BONUS_MINIMUM = 5000000000000000000; // $5 uint public constant HOLD_SCORE_CEILING = 1000000000000000000000000000; // 1 RAY uint public constant BUMP_INCREMENT = 100000000000000000; // 0.1x uint public constant HOLD_TIME_MAX = 23670000; // 9 months is the maximum the owner can set with setHoldTimeCeiling(uint) uint public constant BUMP_PRICE_MAX = 100000000000000000; //0.1 ETH is the maximum the owner can set with setBumpPrice(uint) /** * Events */ event LogVaultDeposit(address indexed addr, string indexed potType, uint value); event LogWithdraw(address indexed to, uint eth, uint sai, uint dai); event Transfer(address indexed from, address indexed to, uint tokens); event LogBump(uint indexed from, uint indexed to, uint cost, address indexed by); event LogBurn( address indexed sender, address indexed receiver, uint receivedAt, uint multiplier, uint initialETH, uint etherPrice, uint bountyETH, uint bountyDAI, uint reward ); event LogGive(address indexed sender, address indexed receiver); /** * Modifiers */ modifier shutdownNotActive() { require(shutdown == false, "shutdown activated"); _; } modifier giveRequirementsMet(address _to) { require(address(_to) != address(0), "Invalid address"); require(_to != msg.sender, "Cannot give to yourself"); require(balanceOf(_to) == 0, "Receiver already has a token"); require(_to.balance > 0, "Receiver wallet must not be empty"); _; } /** * External functions */ /// @notice Give somebody a REKT token, along with an optional bounty in ether. /// @param _to The address to send the REKT token to. function give(address _to) external payable shutdownNotActive giveRequirementsMet(_to) { if (msg.value > 0) { unredeemedBounty[msg.sender].ETH = unredeemedBounty[msg.sender].ETH.add(msg.value); bountyPot.ETH = bountyPot.ETH.add(msg.value); } receiver[_to] = Receiver(_to.balance, msg.value, 0, now, getPrice(), msg.sender); giveCommon(_to); } /// @notice Give somebody a REKT token, along with an option bounty in DAI. /// @param _to The account to send the REKT token to. /// @param _amount The amount of DAI to use as a bounty. function giveWithDAI(address _to, uint _amount) external shutdownNotActive giveRequirementsMet(_to) { if (_amount > 0) { // If the switch has already been included in this block then MCD is active, // but we won't be able to tell later if that's the case so block this tx. // Its ok for the mcd switch to occur later than this function in the same block require(MCDswitchTimestamp != now, "Cannot send DAI during the switching block"); require(dai.transferFrom(msg.sender, address(this), _amount), "DAI transfer failed"); unredeemedBounty[msg.sender].DAI = unredeemedBounty[msg.sender].DAI.add(_amount); bountyPot.DAI = bountyPot.DAI.add(_amount); } receiver[_to] = Receiver(_to.balance, 0, _amount, now, getPrice(), msg.sender); giveCommon(_to); } /// @notice Bump the multiplier up or down. /// @dev Multiplier has PRECISION precision and is rounded down unless the unrounded /// value hits the MULTIPLIER_CEILING or MULTIPLIER_FLOOR. /// @param _up Boolean representing whether the direction of the bump is up or not. function bump(bool _up) external payable shutdownNotActive { require(msg.value > 0, "Ether required"); uint initialMultiplier = multiplier; // amount = (value/price)*bonus*increment uint bumpAmount = msg.value .wdiv(bumpBasePrice) .wmul(getBonusMultiplier(msg.sender)) .wmul(BUMP_INCREMENT); if (_up) { if (multiplier.add(bumpAmount) >= MULTIPLIER_CEILING) { multiplier = MULTIPLIER_CEILING; } else { multiplier = multiplier.add(roundBumpAmount(bumpAmount)); } } else { if (multiplier > bumpAmount) { if (multiplier.sub(bumpAmount) <= MULTIPLIER_FLOOR) { multiplier = MULTIPLIER_FLOOR; } else { multiplier = multiplier.sub(roundBumpAmount(bumpAmount)); } } else { multiplier = MULTIPLIER_FLOOR; } } emit LogBump(initialMultiplier, multiplier, msg.value, msg.sender); feePot = feePot.add(msg.value); } /// @notice Burn a REKT token. If applicable, fee reward and bounty are sent to user's pots. /// REKT tokens can only be burned if the receiver has made gains >= the multiplier /// (unless we are in shutdown mode). /// @param _receiver The account that currently holds the REKT token. function burn(address _receiver) external { require(balanceOf(_receiver) == 1, "Nothing to burn"); address sender = receiver[_receiver].sender; require( msg.sender == _receiver || msg.sender == sender || (_receiver == address(this) && msg.sender == owner), "Must be token sender or receiver, or must be the owner burning REKT sent to the contract" ); if (!shutdown) { if (receiver[_receiver].walletBalance.wmul(multiplier) > _receiver.balance) { uint balanceValueThen = receiver[_receiver].walletBalance.wmul(receiver[_receiver].etherPrice); uint balanceValueNow = _receiver.balance.wmul(getPrice()); if (balanceValueThen.wmul(multiplier) > balanceValueNow) { revert("Not enough gains"); } } } balance[_receiver] = 0; totalSupply --; emit Transfer(_receiver, address(0), 1); uint feeReward = distributeBurnRewards(_receiver, sender); emit LogBurn( sender, _receiver, receiver[_receiver].timestamp, multiplier, receiver[_receiver].walletBalance, receiver[_receiver].etherPrice, receiver[_receiver].bountyETH, receiver[_receiver].bountyDAI, feeReward); } /// @notice Withdrawal of fee reward, DAI, SAI & ETH bounties for the user. /// @param _addr The account to receive the funds and whose vault the funds will be taken from. function withdraw(address payable _addr) external { require(_addr != address(this), "This contract cannot withdraw to itself"); withdrawCommon(_addr, _addr); } /// @notice Withdraw from the contract's personal vault should anyone send /// REKT to REKT.fyi with a bounty. /// @param _destination The account to receive the funds. function withdrawSelf(address payable _destination) external onlyOwner { withdrawCommon(_destination, address(this)); } /// @dev Sets a new Medianizer address in case of MakerDAO upgrades. /// @param _addr The new address. function setNewMedianizer(address _addr) external onlyOwner { require(address(_addr) != address(0), "Invalid address"); medianizerAddress = _addr; oracle = Medianizer(medianizerAddress); bytes32 price; bool ok; (price, ok) = oracle.peek(); require(ok, "Pricefeed error"); } /// @notice Sets a new DAI token address when MakerDAO upgrades to multicollateral DAI. /// @dev DAI will now be deposited into vault[user].bountyDAI for new bounties instead /// of vault[user].bountySAI. /// If setMCD(address) has been included in the block already, then a user will /// not be able to give a SAI/DAI bounty later in this block. /// We can then determine with certainty whether they sent SAI or DAI when the time /// comes to distribute it to a user's vault. /// New DAI token can only be set once; /// further changes will require shutdown and redeployment. /// @param _addr The new address. function setMCD(address _addr) external onlyOwner { require(!isMCD, "MCD has already been set"); require(address(_addr) != address(0), "Invalid address"); daiAddress = _addr; dai = Dai(daiAddress); isMCD = true; MCDswitchTimestamp = now; } /// @dev Sets a new bump price up to BUMP_PRICE_MAX. /// @param _amount The base price of bumping by BUMP_INCREMENT. function setBumpPrice(uint _amount) external onlyOwner { require(_amount > 0 && _amount <= BUMP_PRICE_MAX, "Price must not be higher than BUMP_PRICE_MAX"); bumpBasePrice = _amount; } /// @dev Sets a new hold time ceiling up to HOLD_TIME_MAX. /// @param _seconds The maximum hold time in seconds before the holdscore becomes 1 RAY. function setHoldTimeCeiling(uint _seconds) external onlyOwner { require(_seconds > 0 && _seconds <= HOLD_TIME_MAX, "Hold time must not be higher than HOLD_TIME_MAX"); holdTimeCeiling = _seconds; } /// @dev Permanent shutdown of the contract. /// No one can give or bump, everyone can burn and withdraw. function setShutdown() external onlyOwner { shutdown = true; } /** * Public functions */ /// @dev The proportion of the value of this bounty in relation to /// the value of all bounties in the system. /// @param _bounty This bounty. /// @return A uint representing the proportion of bounty as a RAY. function calculateBountyProportion(uint _bounty) public view returns (uint) { return _bounty.rdiv(potValue(bountyPot.DAI, bountyPot.ETH)); } /// @dev A score <= 1 RAY that corresponds to a duration between 0 and HOLD_SCORE_CEILING. /// @params _receivedAtTime The timestamp of the block where the user received the REKT token. /// @return A uint representing the score as a RAY. function calculateHoldScore(uint _receivedAtTime) public view returns (uint) { if (now == _receivedAtTime) { return 0; } uint timeDiff = now.sub(_receivedAtTime); uint holdScore = timeDiff.rdiv(holdTimeCeiling); if (holdScore > HOLD_SCORE_CEILING) { holdScore = HOLD_SCORE_CEILING; } return holdScore; } /// @notice Returns the REKT balance of the specified address. /// @dev Effectively a bool because the balance can only be 0 or 1. /// @param _owner The address to query the balance of. /// @return A uint representing the amount owned by the passed address. function balanceOf(address _receiver) public view returns (uint) { return balance[_receiver]; } /// @notice Returns the total value of _dai and _eth in USD. 1 DAI = $1 is assumed. /// @dev Price of ether taken from MakerDAO's Medianizer via getPrice(). /// @param _dai DAI to use in calculation. /// @param _eth Ether to use in calculation. /// @return A uint representing the total value of the inputs. function potValue(uint _dai, uint _eth) public view returns (uint) { return _dai.add(_eth.wmul(getPrice())); } /// @dev Returns the bonus multiplier represented as a WAD. /// @param _sender The address of the sender. /// @return A uint representing the bonus multiplier as a WAD. function getBonusMultiplier(address _sender) public view returns (uint) { uint bounty = potValue(unredeemedBounty[_sender].DAI, unredeemedBounty[_sender].ETH); uint bonus = WAD; if (bounty >= BOUNTY_BONUS_MINIMUM) { bonus = bounty.wdiv(potValue(bountyPot.DAI, bountyPot.ETH)).add(BONUS_FLOOR); if (bonus > BONUS_CEILING) { bonus = BONUS_CEILING; } } return bonus; } /// @dev Returns the addresses the sender has sent to as an array. /// @param _sender The address of the sender. /// @return An array of recipient addresses. function getRecipients(address _sender) public view returns (address[] memory) { return recipients[_sender]; } /// @dev Returns the price of ETH in USD as per the MakerDAO Medianizer interface. /// @return A uint representing the price of ETH in USD as a WAD. function getPrice() public view returns (uint) { bytes32 price; bool ok; (price, ok) = oracle.peek(); require(ok, "Pricefeed error"); return uint(price); } /** * Private functions */ /// @dev Common functionality for give(address) and giveWithDAI(address, uint). /// @param _to The account to send the REKT token to. function giveCommon(address _to) private { balance[_to] = 1; recipients[msg.sender].push(_to); totalSupply ++; emit Transfer(address(0), msg.sender, 1); emit Transfer(msg.sender, _to, 1); emit LogGive(msg.sender, _to); } /// @dev Assigns rewards and bounties to pots within user vaults dependant on holdScore /// and bounty proportion compared to the total bounties within the system. /// @param _receiver The account that received the REKT token. /// @param _sender The account that sent the REKT token. /// @return A uint representing the fee reward. function distributeBurnRewards(address _receiver, address _sender) private returns (uint feeReward) { feeReward = 0; uint bountyETH = receiver[_receiver].bountyETH; uint bountyDAI = receiver[_receiver].bountyDAI; uint bountyTotal = potValue(bountyDAI, bountyETH); if (bountyTotal > 0 ) { uint bountyProportion = calculateBountyProportion(bountyTotal); uint userRewardPot = bountyProportion.rmul(feePot); if (shutdown) { // in the shutdown state the holdscore isn't used feeReward = userRewardPot; } else { uint holdScore = calculateHoldScore(receiver[_receiver].timestamp); feeReward = userRewardPot.rmul(holdScore); } if (bountyETH > 0) { // subtract bounty from the senders's bounty total and the bounty pot unredeemedBounty[_sender].ETH = unredeemedBounty[_sender].ETH.sub(bountyETH); bountyPot.ETH = bountyPot.ETH.sub(bountyETH); // add bounty to receivers vault vault[_receiver].bountyETH = vault[_receiver].bountyETH.add(bountyETH); emit LogVaultDeposit(_receiver, 'bountyETH', bountyETH); } else if (bountyDAI > 0) { unredeemedBounty[_sender].DAI = unredeemedBounty[_sender].DAI.sub(bountyDAI); bountyPot.DAI = bountyPot.DAI.sub(bountyDAI); if (isMCD && receiver[_receiver].timestamp > MCDswitchTimestamp) { vault[_receiver].bountyDAI = vault[_receiver].bountyDAI.add(bountyDAI); } else { // they would have sent SAI vault[_receiver].bountySAI = vault[_receiver].bountySAI.add(bountyDAI); } emit LogVaultDeposit(_receiver, 'bountyDAI', bountyDAI); } if (feeReward > 0) { feeReward = feeReward / 2; // subtract and add feeReward for receiver vault feePot = feePot.sub(feeReward); vault[_receiver].fee = vault[_receiver].fee.add(feeReward); emit LogVaultDeposit(_receiver, 'reward', feeReward); // subtract and add feeReward for sender vault feePot = feePot.sub(feeReward); vault[_sender].fee = vault[_sender].fee.add(feeReward); emit LogVaultDeposit(_sender, 'reward', feeReward); } } return feeReward; } /// @dev Returns a rounded bump amount represented as a WAD. /// @param _amount The amount to be rounded. /// @return A uint representing the amount rounded to PRECISION as a WAD. function roundBumpAmount(uint _amount) private pure returns (uint rounded) { require(_amount >= PRECISION, "bump size too small to round"); return (_amount / PRECISION).mul(PRECISION); } /// @dev called by withdraw(address) and withdrawSelf(address) to withdraw /// fee reward, DAI, SAI & ETH bounties. /// Both params will be the same for a normal user withdrawal. /// @param _destination The account to receive the funds. /// @param _vaultOwner The vault that the funds will be taken from. function withdrawCommon(address payable _destination, address _vaultOwner) private { require(address(_destination) != address(0), "Invalid address"); uint amountETH = vault[_vaultOwner].fee.add(vault[_vaultOwner].bountyETH); uint amountDAI = vault[_vaultOwner].bountyDAI; uint amountSAI = vault[_vaultOwner].bountySAI; vault[_vaultOwner] = Vault(0,0,0,0); emit LogWithdraw(_destination, amountETH, amountSAI, amountDAI); if (amountDAI > 0) { require(dai.transferFrom(address(this), _destination, amountDAI), "DAI transfer failed"); } if (amountSAI > 0) { require(sai.transferFrom(address(this), _destination, amountSAI), "SAI transfer failed"); } if (amountETH > 0) { _destination.transfer(amountETH); } } }
Bump the multiplier up or down. Multiplier has PRECISION precision and is rounded down unless the unrounded value hits the MULTIPLIER_CEILING or MULTIPLIER_FLOOR. _up Boolean representing whether the direction of the bump is up or not. amount = (value/price)bonusincrement
function bump(bool _up) external payable shutdownNotActive { require(msg.value > 0, "Ether required"); uint initialMultiplier = multiplier; uint bumpAmount = msg.value .wdiv(bumpBasePrice) .wmul(getBonusMultiplier(msg.sender)) .wmul(BUMP_INCREMENT); if (_up) { if (multiplier.add(bumpAmount) >= MULTIPLIER_CEILING) { multiplier = MULTIPLIER_CEILING; multiplier = multiplier.add(roundBumpAmount(bumpAmount)); } } else { if (multiplier > bumpAmount) { if (multiplier.sub(bumpAmount) <= MULTIPLIER_FLOOR) { multiplier = MULTIPLIER_FLOOR; multiplier = multiplier.sub(roundBumpAmount(bumpAmount)); } } else { multiplier = MULTIPLIER_FLOOR; } } emit LogBump(initialMultiplier, multiplier, msg.value, msg.sender); feePot = feePot.add(msg.value); }
1,033,112
// SPDX-License-Identifier: MIT // Copyright 2021 Mosaic Labs UG, Berlin pragma solidity >=0.8.0 <0.9.0; import "./IERC20Burnable.sol"; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; /** * @title Raffle contract for NFTs * @author Benjamin Bollen <ben@mosaiclabs.eu> */ contract Raffle { /* Constants */ /** * CHALLENGE_WINDOW sets the minimal number of blocks during which * the initial or challenger precommits can be challenged or voted upon. * For each new precommit, the challenge window is restored in full. * Set to 1 hour (300 times 12 second blocks). */ uint256 public constant CHALLENGE_WINDOW = uint256(300); /** * ENTROPY_WINDOW waits for some blocks to collect future block hashes * as a randomizer of the raffle. */ uint256 public constant ENTROPY_WINDOW = uint256(20); /** * ENTROPY_LENGTH takes three consecutive block hashes to create * a randomizer for the raffle. */ uint256 public constant ENTROPY_LENGTH = uint256(3); /** * NOMINATION_COOLDOWN sets the number of blocks during which * entries can be proposed to be sorted as closest to target. * Set to 10 minutes (50 times 12 second blocks). */ uint256 public constant NOMINATION_COOLDOWN = uint256(50); /** * MINIMUM_WEIGHT sets the minimum amount of mechanics token * the organiser must provide on creating a new raffle. */ uint256 public constant MINIMUM_WEIGHT = uint256(10**18); /** * SENTINEL_DISTANCE set to maximum distance. */ uint256 public constant SENTINEL_DISTANCE = uint256( 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ); /** * SENTINEL_TICKETS is reserved bytes32 to identify the end of circular list. */ bytes32 public constant SENTINEL_TICKETS = bytes32( 0x0000000000000000000000000000000000000000000000000000000000000001 ); /* Enums */ /** * Raffle status enum */ enum RaffleStatus { /** * Raffle created. NFT rewards can be added, or taken back by organiser, * raffle metadata and data is collected on OST chain. */ Created, /** * OrganiserPrecommitted. All metadata and all valid transactions * that constitute the raffle tickets have been included into blocks. * Indexers can compute the precommit root of the raffle. * The initial precommit must be presented by the organiser * of the raffle. * Afterwards the precommit can be challenged and arbiter is left to decide. */ OrganiserPrecommitted, /** * Precommitted. Wait for future entropy from Ethereum mainnet. */ Precommitted, /* * Drawn. With new entropy provided by a sequence of Ethereum blockhashes * the raffle is now decided. To verify the winners, the elected raffle * tickets can now be submitted. */ Drawn, /** * Cooled down. The elected raffle tickets have been presented, and * the beneficiary addresses associated with the elected tickets * can be revealed. */ CooledDown, /** * Awarded. All rewards have been awarded to the beneficiary addresses. * This raffle is successfully completed. */ Awarded, /** * Cancelled. The raffle was cancelled before distribution completed. */ Cancelled, /** * Proposed precommit was challenged, and raffle handed over to arbiter. */ Challenged } /* Structs */ /** * Raffle holds essential data and references for the raffle. */ struct RaffleData { // Organiser address who initiated organises the raffle address organiser; // ChainId EIP-155 of where the raffle is distributed uint256 chainId; // Metadata contract on chain with chainId for indexing // all valid raffle tickets address metadata; // Reward ERC721 NFT token contract IERC721 rewardToken; // Weight sets the initial amount of OST token by the organiser. // All other token costs are relative to this weight for the raffle. uint256 weight; // Status enum of raffle RaffleStatus status; } /* Storage */ /** * ERC20 token contract used for mechanics. * On Ethereum mainnet set to OST @ 0x2c4e8f2d746113d0696ce89b35f0d8bf88e0aeca */ IERC20Burnable public token; /** * Arbiter is designated to resolve the precommit if the precommit got challenged. */ address public arbiter; /** * ChainId restriction allows to set the contract to only accept raffles * from a preset chainId. This allows the arbiter to restrict about which * chains it will accept formulating an opinion over. */ uint256 public chainIdRestriction; /** Index counts the number of raffles created */ uint256 public index; /** Reward tokenIds keeps a record of all the ERC721 tokenIds * for each raffle index. * Note that each raffle has a specified ERC721 address. */ mapping(uint256 => uint256[]) public rewardTokenIds; /** * Raffles stores essential data and references for the active raffles. */ mapping(uint256 => RaffleData) public raffles; /** * TimeWindow keeps the block number for the active phase of a raffle * when raffle status is * - OrganiserPrecommitted, time window is set to blocknumber + CHALLENGE_WINDOW * after this the raffle can become precommitted. * During this window the precommit can be challenged and the decision * is handed over to the arbiter. * - Precommitted. The time window is set to allow entropy from Ethereum * to happen after a root has been precomitted. */ mapping(uint256 => uint256) public timeWindows; /** * Precommits stores the precommit as proposed by the raffle organiser. */ mapping(uint256 => bytes32) public precommits; /** * Challengers keep the addresses of the challenger if a precommit * is challenged. */ mapping(uint256 => address) public challengers; /** * Seeds stores the randomizers seeds as generated during draw. */ mapping(uint256 => bytes32) public seeds; /** * Nomination count keeps a count of nominated tickets for a raffle index. * The nomination count increases until it reaches the amount of tokenIds * that are associated to the given raffle. This maximum is present * because we only need to keep nominated tickets for each reward. */ mapping(uint256 => uint256) public nominationCount; /** * Nominations stores the closest tickets thusfar entered into the drawn raffle. */ mapping(uint256 => mapping(bytes32 => bytes32)) public nominations; /* Modifiers */ modifier onlyOrganiser(uint256 _index) { require( raffles[_index].organiser == msg.sender, "Only organiser can call this function." ); _; } modifier onlyArbiter() { require( msg.sender == arbiter, "Only arbiter can call this function." ); _; } modifier isInCreationPhase(uint256 _index) { require( raffles[_index].status == RaffleStatus.Created, "Raffle must be created and not yet precommited." ); _; } modifier isInChallengePhase(uint256 _index) { require( raffles[_index].status == RaffleStatus.OrganiserPrecommitted, "Raffle must have a precommit proposed." ); _; } modifier hasBeenChallenged(uint256 _index) { require( raffles[_index].status == RaffleStatus.Challenged, "Raffle must have been challenged." ); _; } modifier isInPrecommittedPhase(uint256 _index) { require( raffles[_index].status == RaffleStatus.Precommitted, "Raffle must have been precommitted." ); _; } modifier isInDrawnPhase(uint256 _index) { require( raffles[_index].status == RaffleStatus.Drawn, "Raffle must have been drawn." ); _; } /* Constructor */ /** * On construction the token contract for the raffle mechanics must be set. */ constructor( IERC20Burnable _token, address _arbiter, uint256 _chainIdRestriction ) { require( address(_token) != address(0), "The token address cannot be the zero address." ); require( _arbiter != address(0), "The arbiter address cannot be the zero address." ); console.log("Deploying raffle contract with token ", address(_token)); token = _token; arbiter = _arbiter; // restriction can be zero if unrestricted chainIdRestriction = _chainIdRestriction; } /* External Functions */ function createRaffle( uint256 _chainId, address _metadata, IERC721 _rewardToken, uint256[] calldata _tokenIds, uint256 _weight ) external returns (uint256 index_) { require( _chainId != uint256(0), "ChainId provided cannot be zero." ); require( _chainId == uint256(chainIdRestriction) || chainIdRestriction == uint256(0), "Arbiter will only form an opinion on the restricted chainId." ); require( _metadata != address(0), "Metadata contract provided cannot be the zero address." ); require( address(_rewardToken) != address(0), "Reward token address cannot point to the zero address." ); require( _weight > MINIMUM_WEIGHT, "Weight in token amount must be more or equal to 10**18 aOST." ); // Use current index value to index new raffle index_ = index; index = index + 1; // Transfer the weight in OST to the raffle contract token.transferFrom(msg.sender, address(this), _weight); uint256[] storage newTokenIds = rewardTokenIds[index_]; // Transfer all the NFT rewards into the raffle contract // Note, for simplicity this is done during creation, but can be altered for (uint64 i = 0; i < _tokenIds.length; i++ ) { // store the tokenIds that are being assigned to the raffle newTokenIds.push(_tokenIds[i]); _rewardToken.transferFrom(msg.sender, address(this), _tokenIds[i]); } // Initiate new raffle data RaffleData storage raffle = raffles[index_]; raffle.organiser = msg.sender; raffle.chainId = _chainId; raffle.metadata = _metadata; raffle.rewardToken = _rewardToken; raffle.weight = _weight; raffle.status = RaffleStatus.Created; return index_; } /** * Cancel raffle can be called by the organiser of a raffle, but only while * the status of the raffle is Created, not yet Distributed. * On cancelling, the tokenIds the raffle contract owns for this raffle * are transferred to the organiser address. */ function cancelRaffle( uint256 _index ) external onlyOrganiser(_index) isInCreationPhase(_index) { raffles[_index].status = RaffleStatus.Cancelled; IERC721 raffleRewardToken = raffles[_index].rewardToken; uint256[] storage associatedTokenIds = rewardTokenIds[_index]; // TODO: return weight to organiser // transfer all tokenIds to organiser for (uint256 i = 0; i < associatedTokenIds.length; i++) { raffleRewardToken.transferFrom( address(this), msg.sender, associatedTokenIds[i]); } delete rewardTokenIds[_index]; } /** * Organiser can submit a proposal for the root of the raffle. * It starts a challenge period where independent observers can challenge * the proposed commit, leaving the final decision up to the arbiter. */ function proposePrecommit( uint256 _index, bytes32 _precommit ) external onlyOrganiser(_index) isInCreationPhase(_index) { require( _precommit != bytes32(0), "Precommit cannot be zero bytes." ); raffles[_index].status = RaffleStatus.OrganiserPrecommitted; // store the proposed precommit by the organiser precommits[_index] = _precommit; // set time window to expire after challenge window; timeWindows[_index] = block.number + CHALLENGE_WINDOW; } /** * ChallengePrecommit allows anyone to challenge the precommit * presented by the raffle organiser. The challenger must deposit * the same weight in the token. * The final decision on the precommit is handed over to the arbiter. */ function challengePrecommit( uint256 _index ) external isInChallengePhase(_index) { raffles[_index].status = RaffleStatus.Challenged; // Pull in the same amount of token as set in weight token.transferFrom(msg.sender, address(this), raffles[_index].weight); challengers[_index] = msg.sender; } /** * Arbitrate in favour of challenger, and present final precommit. * Half of weight put forward by organiser is burnt; * Half of weight of organiser is awarded to challenger; * Challengers' weight returned to challenger. */ function arbitrateRaffeForChallenger( uint256 _index, bytes32 _decision ) external onlyArbiter() hasBeenChallenged(_index) { require( _decision != bytes32(0), "Decision cannot be zero bytes." ); require( _decision != precommits[_index], "Decision must differ from organisers precommit." ); raffles[_index].status = RaffleStatus.Precommitted; // set the future blockheight at which we can calculate a randomizer timeWindows[_index] = block.number + ENTROPY_WINDOW; // overwrite precommit for raffle precommits[_index] = _decision; address challenger = challengers[_index]; delete challengers[_index]; uint256 weight = raffles[_index].weight; uint256 burnAmount = weight / 2; // ensure sum is exact amounts present in balance; under division errors uint256 rewardAmount = 2 * weight - burnAmount; // burn half the weight token.burn(burnAmount); // award 3/2 of weight to challenger token.transfer(challenger, rewardAmount); } /** * Arbitrate in favour of organisers precommit. * Weight put forward by challenger is burnt; * weight of organiser is returned to organiser. */ function arbitrateRaffeForOrganiser( uint256 _index ) external onlyArbiter() hasBeenChallenged(_index) { raffles[_index].status = RaffleStatus.Precommitted; // set the future blockheight at which we can calculate a randomizer timeWindows[_index] = block.number + ENTROPY_WINDOW; delete challengers[_index]; uint256 weight = raffles[_index].weight; // burn the weight from challenger token.burn(weight); // reimburse weight to organiser token.transfer(raffles[_index].organiser, weight); } /** * Precommit can be called when the challenge period of a proposed precommit * has passed. It then starts the entropy window to randomize the raffle. */ function precommit( uint256 _index ) external isInChallengePhase(_index) { require( timeWindows[_index] <= block.number, "Minimal challenge period must have expired before precommitting." ); raffles[_index].status = RaffleStatus.Precommitted; // set the future blockheight at which we can calculate a randomizer timeWindows[_index] = block.number + ENTROPY_WINDOW; } /** * Draw raffle once the future block hashes are known to randomize the raffle. * Note that only the last 256 ethereum block hashes are available to the EVM * so if too much time has passed, then the raffle must be reshuffled first. */ function drawRaffle( uint256 _index ) external isInPrecommittedPhase(_index) { uint256 endBlock = timeWindows[_index]; uint256 beginBlock = endBlock + uint256(1) - ENTROPY_LENGTH; require( endBlock < block.number, "The entropy window must have passed before raffle can be drawn." ); require( beginBlock + uint256(256) >= block.number, "The window for accessing the block hashes has passed." ); raffles[_index].status = RaffleStatus.Drawn; seeds[_index] = hashBlockSegment(_index, beginBlock); timeWindows[_index] = block.number + NOMINATION_COOLDOWN; } /** * Reshuffle allows the raffle to be unblocked if the access window has passed * where the EVM can access the fixed blockhashes; * reshuffle and draw again within (256 - ENTROPY_LENGTH) blocks window. */ function reshuffleRaffle( uint256 _index ) external isInPrecommittedPhase(_index) { uint256 windowPassedBlock = timeWindows[_index] + uint256(256) - ENTROPY_LENGTH; require( windowPassedBlock < block.number, "The drawing window has not yet passed, call draw() instead." ); // reset the future blockheight at which we can calculate a randomizer timeWindows[_index] = block.number + ENTROPY_WINDOW; } function nominateTickets( uint256 _index, bytes32[] calldata _tickets, bytes32 _furtherTicket ) external isInDrawnPhase(_index) { require( _tickets.length > 0 && _tickets.length <= rewardTokenIds[_index].length, "No more tickets allowed than rewards." ); require( nominations[_index][_furtherTicket] != bytes32(0), "Further ticket must be nominated." ); bytes32 seed = seeds[_index]; // Set distance to further ticket uint256 dFurtherTicket = SENTINEL_DISTANCE; if (_furtherTicket != SENTINEL_TICKETS) { dFurtherTicket = distanceToSeed(_furtherTicket, seed); } bytes32 furtherTicket = _furtherTicket; bytes32 nearerTicket = nominations[_index][_furtherTicket]; for(uint256 i = 0; i < _tickets.length; i++) { bytes32 ticket = _tickets[i]; require( ticket != bytes32(0) && ticket != SENTINEL_TICKETS, "Ticket cannot be zero bytes or sentinel bytes." ); require( nominations[_index][ticket] == bytes32(0), "Ticket cannot already be nominated." ); // first calculate distance uint256 distanceTicket = distanceToSeed(ticket, seed); require( distanceTicket < dFurtherTicket, "Ticket must be nearer than further away ticket." ); while (nearerTicket != SENTINEL_TICKETS) { // continue } } } /* Public Functions */ /** * Distance to seed takes a ticket and a seed, first hashes the ticket * bytes with the seed, and then calculates the XOR distance to the seed * producing a randomised order over the tickets. */ function distanceToSeed( bytes32 _ticket, bytes32 _seed ) public pure returns (uint256 distance_) { distance_ = distance(shuffleTicket(_ticket, _seed), _seed); } /* Private Functions */ /** * hashBlockSegment will hash together a sequence of blockhashes of length * ENTROPY_LENGTH starting at `_beginBlock`, additionally including * the raffle index and address of raffle contract to ensure * a unique seed for each raffle. */ function hashBlockSegment( uint256 _index, uint256 _beginBlock ) private view returns (bytes32 seed_) { bytes32[] memory seedGenerator = new bytes32[](ENTROPY_LENGTH); for (uint256 i = 0; i < ENTROPY_LENGTH; i++) { seedGenerator[i] = blockhash(_beginBlock + i); } seed_ = keccak256( abi.encodePacked( address(this), _index, seedGenerator ) ); } /** * Shuffle ticket additionally randomises the bits of the tickets, * even though strictly speaking the XOR distance measured from * a fixed random seed, already randomises the ordering of tickets. * But because we only need to hash the nominated tickets, we can * additionally randomise the ticket bytes prior to checking the distance * to the random seed. */ function shuffleTicket( bytes32 _ticket, bytes32 _seed ) private pure returns (bytes32 shuffledTicket_) { shuffledTicket_ = keccak256( abi.encodePacked( _ticket, _seed ) ); } /** * distance returns the XOR distance between two 32 byte values. * Beyond satisfying the required distance properties, * d(a, . ) is unique, making it useful to sort elements. * Additionally XOR is a perfect cypher for a message and key of equal length * so if `_a` is random, XOR randomises the ordering of all `_b`. * Nonetheless we additionally hash the tickets to randomise their bits as well. */ function distance(bytes32 _a, bytes32 _b) private pure returns (uint256 distance_) { // return XOR(_a, _b) distance, which has the additional property // that for fixed _a, the distance to _b is unique to _b. distance_ = uint256(_a ^ _b); } }
Draw raffle once the future block hashes are known to randomize the raffle. Note that only the last 256 ethereum block hashes are available to the EVM so if too much time has passed, then the raffle must be reshuffled first./
function drawRaffle( uint256 _index ) external isInPrecommittedPhase(_index) { uint256 endBlock = timeWindows[_index]; uint256 beginBlock = endBlock + uint256(1) - ENTROPY_LENGTH; require( endBlock < block.number, "The entropy window must have passed before raffle can be drawn." ); require( beginBlock + uint256(256) >= block.number, "The window for accessing the block hashes has passed." ); raffles[_index].status = RaffleStatus.Drawn; seeds[_index] = hashBlockSegment(_index, beginBlock); timeWindows[_index] = block.number + NOMINATION_COOLDOWN; }
935,809
pragma solidity ^0.4.17; import "zos-lib/contracts/Initializable.sol"; import "zeppelin-solidity/contracts/MerkleProof.sol"; import "zeppelin-solidity/contracts/token/ERC20.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title MerkleMine * @dev Token distribution based on providing Merkle proofs of inclusion in genesis state to generate allocation */ contract MerkleMine is Initializable { using SafeMath for uint256; // ERC20 token being distributed ERC20 public token; // Merkle root representing genesis state which encodes token recipients bytes32 public genesisRoot; // Total amount of tokens that can be generated uint256 public totalGenesisTokens; // Total number of recipients included in genesis state uint256 public totalGenesisRecipients; // Amount of tokens per recipient allocation. Equal to `totalGenesisTokens` / `totalGenesisRecipients` uint256 public tokensPerAllocation; // Minimum ETH balance threshold for recipients included in genesis state uint256 public balanceThreshold; // Block number of genesis - used to determine which ETH accounts are included in the genesis state uint256 public genesisBlock; // Start block where a third party caller (not the recipient) can generate and split the allocation with the recipient // As the current block gets closer to `callerAllocationEndBlock`, the caller receives a larger precentage of the allocation uint256 public callerAllocationStartBlock; // From this block onwards, a third party caller (not the recipient) can generate and claim the recipient's full allocation uint256 public callerAllocationEndBlock; // Number of blocks in the caller allocation period as defined by `callerAllocationEndBlock` - `callerAllocationStartBlock` uint256 public callerAllocationPeriod; // Track if the generation process is started bool public started; // Track the already generated allocations for recipients mapping (address => bool) public generated; // Check that a recipient's allocation has not been generated modifier notGenerated(address _recipient) { require(!generated[_recipient]); _; } // Check that the generation period is started modifier isStarted() { require(started); _; } // Check that the generation period is not started modifier isNotStarted() { require(!started); _; } event Generate(address indexed _recipient, address indexed _caller, uint256 _recipientTokenAmount, uint256 _callerTokenAmount, uint256 _block); /** * @dev MerkleMine constructor * @param _token ERC20 token being distributed * @param _genesisRoot Merkle root representing genesis state which encodes token recipients * @param _totalGenesisTokens Total amount of tokens that can be generated * @param _totalGenesisRecipients Total number of recipients included in genesis state * @param _balanceThreshold Minimum ETH balance threshold for recipients included in genesis state * @param _genesisBlock Block number of genesis - used to determine which ETH accounts are included in the genesis state * @param _callerAllocationStartBlock Start block where a third party caller (not the recipient) can generate and split the allocation with the recipient * @param _callerAllocationEndBlock From this block onwards, a third party caller (not the recipient) can generate and claim the recipient's full allocation */ function initialize( address _token, bytes32 _genesisRoot, uint256 _totalGenesisTokens, uint256 _totalGenesisRecipients, uint256 _balanceThreshold, uint256 _genesisBlock, uint256 _callerAllocationStartBlock, uint256 _callerAllocationEndBlock ) public initializer { // Address of token contract must not be null require(_token != address(0)); // Number of recipients must be non-zero require(_totalGenesisRecipients > 0); // Genesis block must be at or before the current block require(_genesisBlock <= block.number); // Start block for caller allocation must be after current block require(_callerAllocationStartBlock > block.number); // End block for caller allocation must be after caller allocation start block require(_callerAllocationEndBlock > _callerAllocationStartBlock); token = ERC20(_token); genesisRoot = _genesisRoot; totalGenesisTokens = _totalGenesisTokens; totalGenesisRecipients = _totalGenesisRecipients; tokensPerAllocation = _totalGenesisTokens.div(_totalGenesisRecipients); balanceThreshold = _balanceThreshold; genesisBlock = _genesisBlock; callerAllocationStartBlock = _callerAllocationStartBlock; callerAllocationEndBlock = _callerAllocationEndBlock; callerAllocationPeriod = _callerAllocationEndBlock.sub(_callerAllocationStartBlock); } /** * @dev Start the generation period - first checks that this contract's balance is equal to `totalGenesisTokens` * The generation period must not already be started */ function start() external isNotStarted { // Check that this contract has a sufficient balance for the generation period require(token.balanceOf(this) >= totalGenesisTokens); started = true; } /** * @dev Generate a recipient's token allocation. Generation period must be started. Starting from `callerAllocationStartBlock` * a third party caller (not the recipient) can invoke this function to generate the recipient's token * allocation and claim a percentage of it. The percentage of the allocation claimed by the * third party caller is determined by how many blocks have elapsed since `callerAllocationStartBlock`. * After `callerAllocationEndBlock`, a third party caller can claim the full allocation * @param _recipient Recipient of token allocation * @param _merkleProof Proof of recipient's inclusion in genesis state Merkle root */ function generate(address _recipient, bytes _merkleProof) external isStarted notGenerated(_recipient) { // Check the Merkle proof bytes32 leaf = keccak256(_recipient); // _merkleProof must prove inclusion of _recipient in the genesis state root require(MerkleProof.verifyProof(_merkleProof, genesisRoot, leaf)); generated[_recipient] = true; address caller = msg.sender; if (caller == _recipient) { // If the caller is the recipient, transfer the full allocation to the caller/recipient require(token.transfer(_recipient, tokensPerAllocation)); Generate(_recipient, _recipient, tokensPerAllocation, 0, block.number); } else { // If the caller is not the recipient, the token allocation generation // can only take place if we are in the caller allocation period require(block.number >= callerAllocationStartBlock); uint256 callerTokenAmount = callerTokenAmountAtBlock(block.number); uint256 recipientTokenAmount = tokensPerAllocation.sub(callerTokenAmount); if (callerTokenAmount > 0) { require(token.transfer(caller, callerTokenAmount)); } if (recipientTokenAmount > 0) { require(token.transfer(_recipient, recipientTokenAmount)); } Generate(_recipient, caller, recipientTokenAmount, callerTokenAmount, block.number); } } /** * @dev Return the amount of tokens claimable by a third party caller when generating a recipient's token allocation at a given block * @param _blockNumber Block at which to compute the amount of tokens claimable by a third party caller */ function callerTokenAmountAtBlock(uint256 _blockNumber) public view returns (uint256) { if (_blockNumber < callerAllocationStartBlock) { // If the block is before the start of the caller allocation period, the third party caller can claim nothing return 0; } else if (_blockNumber >= callerAllocationEndBlock) { // If the block is at or after the end block of the caller allocation period, the third party caller can claim everything return tokensPerAllocation; } else { // During the caller allocation period, the third party caller can claim an increasing percentage // of the recipient's allocation based on a linear curve - as more blocks pass in the caller allocation // period, the amount claimable by the third party caller increases linearly uint256 blocksSinceCallerAllocationStartBlock = _blockNumber.sub(callerAllocationStartBlock); return tokensPerAllocation.mul(blocksSinceCallerAllocationStartBlock).div(callerAllocationPeriod); } } }
Start the generation period - first checks that this contract's balance is equal to `totalGenesisTokens` The generation period must not already be started/ Check that this contract has a sufficient balance for the generation period
function start() external isNotStarted { require(token.balanceOf(this) >= totalGenesisTokens); started = true; }
5,360,572
/** *Submitted for verification at Etherscan.io on 2021-09-29 */ // Contract based on https://docs.openzeppelin.com/contracts/4.x/erc721 // SPDX-License-Identifier: MIT // Pixel PepePunks // pepunks.com // pragma solidity ^0.8.0; 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) { 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); } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } 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); } } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } /** * @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}. * * IMPORTANT CHANGES !!! * _owners: visibility set to internal. * _balances: visibility set to internal. * _checkOnERC721Received: removed * All calls from contract ERC721 set to overwritables. For example, ERC721.ownerOf(tokenId) set to ownerOf(tokenId). */ 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) internal _owners; // Mapping owner address to token count mapping(address => uint256) internal _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @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 = 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. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); } /** * @dev Returns whether `tokenId` exists. */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. */ 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); } /** * @dev Mints `tokenId` and transfers it to `to`. */ 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. */ function _burn(uint256 tokenId) internal virtual { address owner = 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. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(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. */ /*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. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * ERC721 with premint feautures. Premint owner can't be null address. */ contract ERC721Premint is ERC721 { uint256 private _premintedCount; address private _premintOwner; uint256 private _mintedCount; mapping(uint256 => bool) private _burned; constructor(string memory name_, string memory symbol_, address premintOwner_) ERC721(name_, symbol_) { _premintOwner = premintOwner_ == address(0) ? _msgSender() : premintOwner_; } // ------------------ IERC721 Overrides --------------- function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return super.balanceOf(owner) + (_isPremintOwner(owner) ? _premintedCount : 0); } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; if (isPremintedToken(tokenId)){ owner = _premintOwner; } require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function _exists(uint256 tokenId) internal view virtual override returns (bool) { return _owners[tokenId] != address(0) || isPremintedToken(tokenId); } function _mint(address to, uint256 tokenId) internal virtual override { super._mint(to, tokenId); _mintedCount += 1; } function _burn(uint256 tokenId) internal virtual override { require(!isPremintedToken(tokenId), "Premint: burning preminted token"); super._burn(tokenId); _burned[tokenId] = true; } function _transfer(address from, address to, uint256 tokenId) internal override virtual { bool _isPremintedToken = isPremintedToken(tokenId); require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); require(!_isPremintedToken || !_isPremintOwner(to), "Premint: transfer preminted token to the Premint Owner"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); if (_isPremintOwner(from) && _isPremintedToken){ _premintedCount -= 1; _mintedCount += 1; } else { _balances[from] -= 1; } _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } // ------------------ IERC721Premint and utils --------------- function _totalSupply() internal view returns (uint256) { return _mintedCount + _premintedCount; } function _isPremintOwner(address addr) internal view returns (bool) { return _premintOwner == addr; } function originBalanceOf(address owner) public view virtual returns (uint256) { return super.balanceOf(owner); } function originOwnerOf(uint256 tokenId) public view virtual returns (address) { return super.ownerOf(tokenId); } function premintOwner() public virtual view returns (address) { return _premintOwner; } function premintedCount() public virtual view returns (uint256) { return _premintedCount; } function isPremintedToken(uint256 tokenId) public view virtual returns (bool) { return _owners[tokenId] == address(0) && !_burned[tokenId] && tokenId <= _totalSupply(); } function mintedCount() public virtual view returns (uint256) { return _mintedCount; } function _premint(uint256 count) internal virtual { require(count > 0, "Premint: premint count is zero"); uint256 startTokenId = _totalSupply() + 1; _premintedCount += count; for(uint256 i = 0; i < count; i++){ emit Transfer(address(0), _premintOwner, startTokenId + i); } } } /** * ERC721Premint with sequential token indexes and others features. */ contract ERC721PremintBasic is ERC721Premint, IERC721Enumerable, Ownable { using Strings for uint256; mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; string private _baseUri; // Storage: tokenURIs mapping(uint256 => string) private _tokenURIs; constructor(string memory name_, string memory symbol_, address premintOwner_) ERC721Premint(name_, symbol_, premintOwner_) {} /** * @dev See {ERC721Premint}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function canMint(address to, uint256 count) public view virtual returns (bool) { require(to != address(0), "Recipient is required"); require(count > 0, "Mint: Count must be 1 or more"); return true; } function canPremint(uint256 count) public view virtual returns (bool) { require(count > 0, "Premint: Count must be 1 or more"); return true; } function mintTo(address to, uint256 count) public onlyOwner { require(canMint(to, count)); for(uint256 i = 0; i < count; i++){ _safeMint(to, totalSupply() + 1); } } function premint(uint256 count) public virtual onlyOwner { require(canPremint(count)); _premint(count); } function burn(uint256 tokenId) public virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } /** * @dev See {IERC721Enumerable}. */ function totalSupply() public view override returns (uint256) { return _totalSupply(); } /** * @dev See {IERC721Enumerable}. */ function tokenOfOwnerByIndex(address owner_, uint256 index) external view override returns (uint256 tokenId) { require(index < balanceOf(owner_), "ERC721Enumerable: owner index out of bounds"); if (_isPremintOwner(owner_)){ // // IMPORTANT !!! Calling with index of preminted tokens throws an error! // require(index < originBalanceOf(owner_), "Premint: Premint Owner index out of bounds"); } return _ownedTokens[owner_][index]; } /** * @dev See {IERC721Enumerable}. * * Important!!! Without throw error when token by index is burned! */ function tokenByIndex(uint256 index) external view override returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return index + 1; } /** * @dev {Storage}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory base = _baseURI(); string memory _tokenURI = _tokenURIs[tokenId]; if (bytes(_tokenURI).length > 0) { return _tokenURI; } return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ""; } /** * @dev {Storage}. */ function baseURI() public view virtual returns (string memory) { return _baseUri; } function setBaseURI(string memory uri) public virtual onlyOwner { _baseUri = uri; } function _baseURI() internal view virtual override returns (string memory) { return _baseUri; } /** * @dev {Storage}. */ function setTokenURI(uint256 tokenId, string memory _tokenURI) public virtual onlyOwner { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { // do nothing } else if (from != to && !isPremintedToken(tokenId)) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { // do nothing } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Premint.originBalanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } 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 = ERC721Premint.originBalanceOf(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]; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } } abstract contract ERC721MysteryBox is ERC721PremintBasic { uint256 private _maxTokens = 5555; mapping(uint256 => address) private _mapBoxesTo; mapping(uint256 => uint256) private _mapBoxesCount; mapping(uint256 => address) private _mapBoxesProxy; mapping(uint256 => string) private _mapBoxesName; uint256 private _reservedForBox; function maxTokens() public view virtual returns (uint256) { return _maxTokens; } function setMaxTokens(uint256 maxTokens_) public virtual onlyOwner { require(maxTokens_ >= totalSupply() + _reservedForBox, "Max count is not correct"); _maxTokens = maxTokens_; } function reservedForMysteryBox() public view returns (uint256) { return _reservedForBox; } function canMint(address to, uint256 count) public view virtual override returns (bool) { if (_maxTokens > 0){ require(_maxTokens >= totalSupply() + count + _reservedForBox, "Exceeds maximum tokens available"); } return super.canMint(to, count); } function isMysteryBoxToken(uint256 tokenId) public view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); return address(_mapBoxesTo[tokenId]) != address(0); } function mysteryBoxInfo(uint256 tokenId) public view returns (uint256 count, string memory name, address proxy) { require(isMysteryBoxToken(tokenId), "Token is not a Mystery Box"); return ( _mapBoxesCount[tokenId], _mapBoxesName[tokenId], _mapBoxesProxy[tokenId] ); } function mintBox(address to, uint256 count, string memory name) public onlyOwner { require(canMint(to, count + 1)); mintBoxProxy(to, count, name, address(0)); } function mintBoxProxy( address to, uint256 count, string memory name, address proxyUnpackerAddress) public onlyOwner { require(canMint(to, count + 1)); uint256 boxId = totalSupply() + 1; _safeMint(to, boxId); _reservedForBox += count; _mapBoxesTo[boxId] = to; _mapBoxesCount[boxId] = count; _mapBoxesProxy[boxId] = proxyUnpackerAddress; _mapBoxesName[boxId] = name; } function unpack(uint256 tokenId) public { require(isMysteryBoxToken(tokenId), "Error: token is not a Mystery Box token"); require(_isApprovedOrOwner(_msgSender(), tokenId), "Caller is not owner or approved"); address to = ownerOf(tokenId); uint256 boxCoint = _mapBoxesCount[tokenId]; if (boxCoint > 0){ for(uint256 i = 0; i < boxCoint; i++){ _safeMint(to, totalSupply() + 1); } _reservedForBox -= boxCoint; } if (_mapBoxesProxy[tokenId] != address(0)){ IProxyUnpacker proxyUnpacker = IProxyUnpacker(_mapBoxesProxy[tokenId]); proxyUnpacker.unpackMysteryBox(to); } // Burn the Mystery Box burn(tokenId); } } /** * @title Interface for contract unpacking Mistery Box */ interface IProxyUnpacker { function unpackMysteryBox(address to) external; } contract PepePunks is ERC721MysteryBox { constructor(address premintOwner) ERC721PremintBasic("PepePunks", "PPP", premintOwner) {} }
See {ERC721Premint}./
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
2,221,590
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; import "../helpers/LiquityHelper.sol"; import "../../../utils/TokenUtils.sol"; import "../../ActionBase.sol"; contract LiquityOpen is ActionBase, LiquityHelper { using TokenUtils for address; struct Params { uint256 maxFeePercentage; // Highest borrowing fee to accept, ranges between 0.5 and 5% uint256 collAmount; // Amount of WETH tokens to supply as collateral uint256 lusdAmount; // Amount of LUSD tokens to borrow from the trove, protocol minimum net debt is 1800 address from; // Address where to pull the collateral from address to; // Address that will receive the borrowed tokens address upperHint; address lowerHint; } /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory params = parseInputs(_callData); params.maxFeePercentage = _parseParamUint( params.maxFeePercentage, _paramMapping[0], _subData, _returnValues ); params.collAmount = _parseParamUint( params.collAmount, _paramMapping[1], _subData, _returnValues ); params.lusdAmount = _parseParamUint( params.lusdAmount, _paramMapping[2], _subData, _returnValues ); params.from = _parseParamAddr(params.from, _paramMapping[3], _subData, _returnValues); params.to = _parseParamAddr(params.to, _paramMapping[4], _subData, _returnValues); uint256 troveOwner = _liquityOpen(params); return bytes32(troveOwner); } /// @inheritdoc ActionBase function executeActionDirect(bytes[] memory _callData) public payable virtual override { Params memory params = parseInputs(_callData); _liquityOpen(params); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Opens up a trove function _liquityOpen(Params memory _params) internal returns (uint256) { if (_params.collAmount == type(uint256).max) { _params.collAmount = TokenUtils.WETH_ADDR.getBalance(_params.from); } TokenUtils.WETH_ADDR.pullTokensIfNeeded(_params.from, _params.collAmount); TokenUtils.withdrawWeth(_params.collAmount); BorrowerOperations.openTrove{value: _params.collAmount}( _params.maxFeePercentage, _params.lusdAmount, _params.upperHint, _params.lowerHint ); LUSDTokenAddr.withdrawTokens(_params.to, _params.lusdAmount); logger.Log( address(this), msg.sender, "LiquityOpen", abi.encode( _params.maxFeePercentage, _params.collAmount, _params.lusdAmount, _params.from, _params.to ) ); return _params.collAmount; } function parseInputs(bytes[] memory _callData) internal pure returns (Params memory params) { params = abi.decode(_callData[0], (Params)); } }
@inheritdoc ActionBase
function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory params = parseInputs(_callData); params.maxFeePercentage = _parseParamUint( params.maxFeePercentage, _paramMapping[0], _subData, _returnValues ); params.collAmount = _parseParamUint( params.collAmount, _paramMapping[1], _subData, _returnValues ); params.lusdAmount = _parseParamUint( params.lusdAmount, _paramMapping[2], _subData, _returnValues ); params.from = _parseParamAddr(params.from, _paramMapping[3], _subData, _returnValues); params.to = _parseParamAddr(params.to, _paramMapping[4], _subData, _returnValues); uint256 troveOwner = _liquityOpen(params); return bytes32(troveOwner); }
5,390,608
./full_match/42220/0x1a8Dbe5958c597a744Ba51763AbEBD3355996c3e/sources/home/home/dotfiles/poofcelo/contracts/RewardsCELO.sol
Deposits wrappedCelo to the contract in exchange for RewardsCELO (pCELO) tokens. pCELO to mint is determined by the equivalence: savingsToCELO(toDeposit) / nextTotalSupplyCELO = toMint / (this.totalSupply() + toMint) and solving for `toMint`. toDeposit amount of wrappedCelo to deposit wrappedCeloIdx index of wrappedCelo that is supported by pCELO
function deposit(uint256 toDeposit, uint256 wrappedCeloIdx) external nonReentrant { require(toDeposit > 0, "Can't deposit a zero amount"); require(wrappedCeloIdx < wrappedCelos.length, "wrappedCeloIdx out of bounds"); IWrappedCelo wrappedCelo = wrappedCelos[wrappedCeloIdx]; require(bans[address(wrappedCelo)] == false, "Selected wrappedCelo is banned"); uint256 totalSupplyCELO = getTotalSupplyCELO(); uint256 celoToAdd = wrappedCelo.savingsToCELO(toDeposit); uint256 nextTotalSupplyCELO = totalSupplyCELO.add(celoToAdd); uint256 toMint; if (totalSupplyCELO == 0) { toMint = toDeposit; toMint = celoToAdd.mul(this.totalSupply()).div(nextTotalSupplyCELO.sub(celoToAdd)); } wrappedCelo.safeTransferFrom(_msgSender(), address(this), toDeposit); _mint(_msgSender(), toMint); }
16,336,002
./partial_match/42/0x88278FA799bd151756C9b68b76D57a38Bb0b51Fc/sources/eMTV.sol
Burns a specific amount of tokens. Only an address listed in `isBurner` can do this. _value The amount of token to be burned./
function burn(uint256 _value) public onlyBurner { super.burn(_value); }
3,406,273
./full_match/1/0x59D55D53a715b3B4581c52098BCb4075C2941DBa/sources/contracts/protocol/modules/v1/AuctionRebalanceModuleV1.sol
Calculates the protocol fee based on the tokens received during the bid and transfers it from the SetToken to the protocol recipient. _bidInfo Struct containing information related to the bid. return uint256 The amount of the received tokens taken as a protocol fee./ Calculate the amount of tokens exchanged during the bid. Calculate the protocol fee. Transfer the protocol fee from the SetToken to the protocol recipient.
function _accrueProtocolFee(BidInfo memory _bidInfo) internal returns (uint256) { IERC20 receiveToken = IERC20(_bidInfo.receiveToken); ISetToken setToken = _bidInfo.setToken; uint256 exchangedQuantity = receiveToken.balanceOf(address(setToken)) .sub(_bidInfo.preBidTokenReceivedBalance); uint256 protocolFee = getModuleFee(AUCTION_MODULE_V1_PROTOCOL_FEE_INDEX, exchangedQuantity); payProtocolFeeFromSetToken(setToken, address(_bidInfo.receiveToken), protocolFee); return protocolFee; }
3,851,279
pragma solidity ^ 0.5.11; contract PoWHr{ // scaleFactor is used to convert Ether into bonds and vice-versa: they're of different // orders of magnitude, hence the need to bridge between the two. uint256 constant scaleFactor = 0x10000000000000000; int constant crr_n = 1; int constant crr_d = 2; int constant public price_coeff = -0x1337FA66607BADA55; // Typical values that we have to declare. string constant public name = "Bond"; string constant public symbol = "BOND"; uint8 constant public decimals = 12; // Array between each address and their number of bonds. mapping(address => uint256) public hodlBonds; // For calculating resolves minted mapping(address => uint256) public avgFactor_ethSpent; // For calculating hodl multiplier that factors into resolves minted mapping(address => uint256) public avgFactor_buyInTimeSum; // Array between each address and their number of resolves being staked. mapping(address => uint256) public resolveWeight; // Array between each address and how much Ether has been paid out to it. // Note that this is scaled by the scaleFactor variable. mapping(address => int256) public payouts; // Variable tracking how many bonds are in existence overall. uint256 public _totalSupply; // The total number of resolves being staked in this contract uint256 public dissolvingResolves; // The total number of resolves burned for a return of ETH(withdraw) or Bonds(reinvest) uint256 public dissolved; // The ethereum locked up into bonds uint public reserves; // Easing in the fee. Make the fee reasonable as the contract is scaling to the size of the ecosystem uint256 public buySum; uint256 public sellSum; // For calculating the hodl multiplier. Weighted average release time uint public avgFactor_releaseWeight; uint public avgFactor_releaseTimeSum; // base time on when the contract was created uint public genesis; // Aggregate sum of all payouts. // Note that this is scaled by the scaleFactor variable. int256 totalPayouts; // Variable tracking how much Ether each token is currently worth. // Note that this is scaled by the scaleFactor variable. uint256 earningsPerResolve; uint remainderForDividends; //The resolve token contract ResolveToken public resolveToken; constructor() public{ genesis = now; resolveToken = new ResolveToken( address(this) ); } function totalSupply() public view returns (uint256) { return _totalSupply; } function getResolveContract() public view returns(address){ return address(resolveToken); } // Returns the number of bonds currently held by _owner. function balanceOf(address _owner) public view returns (uint256 balance) { return hodlBonds[_owner]; } function fluxFee(uint paidAmount) public view returns (uint fee) { if (dissolvingResolves == 0) return 0; uint totalResolveSupply = resolveToken.totalSupply() - dissolved; return paidAmount * dissolvingResolves / totalResolveSupply * sellSum / buySum; } // Converts the Ether accrued as resolveEarnings back into bonds without having to // withdraw it first. Saves on gas and potential price spike loss. event Reinvest( address indexed addr, uint256 reinvested, uint256 dissolved, uint256 bonds, uint256 resolveTax); function reinvestEarnings(uint amountFromEarnings) public returns(uint,uint){ // Retrieve the resolveEarnings associated with the address the request came from. uint totalEarnings = resolveEarnings(msg.sender); require(amountFromEarnings <= totalEarnings, "the amount exceeds total earnings"); uint oldWeight = resolveWeight[msg.sender]; resolveWeight[msg.sender] = oldWeight * (totalEarnings - amountFromEarnings) / totalEarnings; uint weightDiff = oldWeight - resolveWeight[msg.sender]; dissolved += weightDiff; dissolvingResolves -= weightDiff; // For maintaing payout invariance int resolvePayoutDiff = (int256) (earningsPerResolve * weightDiff); payouts[msg.sender] += resolvePayoutDiff; totalPayouts += resolvePayoutDiff; // Assign balance to a new variable. uint value_ = (uint) (amountFromEarnings); // If your resolveEarnings are worth less than 1 szabo, abort. if (value_ < 0.000001 ether) revert(); // msg.sender is the address of the caller. address sender = msg.sender; // Calculate the fee uint fee = fluxFee(value_); // The amount of Ether used to purchase new bonds for the caller uint numEther = value_ - fee; buySum += numEther; reserves += numEther; //resolve reward tracking stuff uint currentTime = NOW(); avgFactor_ethSpent[msg.sender] += numEther; avgFactor_buyInTimeSum[msg.sender] += currentTime * scaleFactor * numEther; // The number of bonds which can be purchased for numEther. uint createdBonds = calculateBondsFromReinvest(numEther, amountFromEarnings); // the variable storing the amount to be paid to stakers uint resolveFee; // Check if we have bonds in existence if (_totalSupply > 0 && fee > 0) { resolveFee = fee * scaleFactor; // Fee is distributed to all existing resolve stakers before the new bonds are purchased. // rewardPerResolve is the amount(ETH) gained per resolve token from this purchase. uint rewardPerResolve = dividendDivide(resolveFee); // The Ether value per token is increased proportionally. earningsPerResolve += rewardPerResolve; } // Add the createdBonds to the total supply. _totalSupply += createdBonds; // Assign the bonds to the balance of the buyer. hodlBonds[sender] += createdBonds; emit Reinvest(msg.sender, value_, weightDiff, createdBonds, resolveFee); return (createdBonds, weightDiff); } function dividendDivide(uint N) internal returns(uint){ uint quotient = N/dissolvingResolves; remainderForDividends += N - quotient * dissolvingResolves; if( remainderForDividends > dissolvingResolves ){ uint divs = remainderForDividends; remainderForDividends = 0; uint rQuotient = divs/dissolvingResolves; earningsPerResolve += rQuotient; remainderForDividends += divs - rQuotient * dissolvingResolves; } return quotient; } // Sells your bonds for Ether function sellAllBonds() public { sell( balanceOf(msg.sender) ); } function sellBonds(uint amount) public returns(uint,uint){ uint balance = balanceOf(msg.sender); require(balance >= amount, "Amount is more than balance"); uint returned_eth; uint returned_resolves; (returned_eth, returned_resolves) = sell(amount); return (returned_eth, returned_resolves); } // Big red exit button to pull all of a holder's Ethereum value from the contract function getMeOutOfHere() public { sellAllBonds(); withdraw( resolveEarnings(msg.sender) ); } // Gatekeeper function to check if the amount of Ether being sent isn't too small function fund() payable public returns(uint){ uint bought; if (msg.value > 0.000001 ether) { bought = buy(); } else { revert(); } return bought; } // Function that returns the (dynamic) pricing for buys, sells and fee function pricing(uint scale) public view returns (uint buyPrice, uint sellPrice, uint fee) { uint buy_eth = scaleFactor * getPriceForBonds( scale, true) / ( scaleFactor - fluxFee(scaleFactor) ) ; uint sell_eth = getPriceForBonds(scale, false); sell_eth -= fluxFee(sell_eth); return ( buy_eth, sell_eth, fluxFee(scale) ); } // For calculating the price function getPriceForBonds(uint256 bonds, bool upDown) public view returns (uint256 price) { uint reserveAmount = reserve(); if(upDown){ uint x = fixedExp((fixedLog(_totalSupply + bonds) - price_coeff) * crr_d/crr_n); return x - reserveAmount; }else{ uint x = fixedExp((fixedLog(_totalSupply - bonds) - price_coeff) * crr_d/crr_n); return reserveAmount - x; } } // Calculate the current resolveEarnings associated with the caller address. This is the net result // of multiplying the number of resolves held by their current value in Ether and subtracting the // Ether that has already been paid out. function resolveEarnings(address _owner) public view returns (uint256 amount) { return (uint256) ((int256)(earningsPerResolve * resolveWeight[_owner]) - payouts[_owner]) / scaleFactor; } event Buy( address indexed addr, uint256 spent, uint256 bonds, uint256 resolveTax); function buy() internal returns(uint){ // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. if ( msg.value < 0.000001 ether ) revert(); // Calculate the fee uint fee = fluxFee(msg.value); // The amount of Ether used to purchase new bonds for the caller. uint numEther = msg.value - fee; buySum += numEther; reserves += numEther; //resolve reward tracking stuff uint currentTime = NOW(); avgFactor_ethSpent[msg.sender] += numEther; avgFactor_buyInTimeSum[msg.sender] += currentTime * scaleFactor * numEther; // The number of bonds which can be purchased for numEther. uint createdBonds = getBondsForEther(numEther); // Add the createdBonds to the total supply. _totalSupply += createdBonds; // Assign the bonds to the balance of the buyer. hodlBonds[msg.sender] += createdBonds; // Check if we have bonds in existence uint resolveFee; if (_totalSupply > 0 && fee > 0) { resolveFee = fee * scaleFactor; // Fee is distributed to all existing resolve holders before the new bonds are purchased. // rewardPerResolve is the amount gained per resolve token from this purchase. uint rewardPerResolve = dividendDivide(resolveFee); // The Ether value per resolve is increased proportionally. earningsPerResolve += rewardPerResolve; } emit Buy( msg.sender, msg.value, createdBonds, resolveFee); return createdBonds; } function NOW() public view returns(uint time){ return now - genesis; } function avgHodl() public view returns(uint hodlTime){ return avgFactor_releaseTimeSum / avgFactor_releaseWeight / scaleFactor; } function getReturnsForBonds(address addr, uint bondsReleased) public view returns(uint etherValue, uint mintedResolves, uint new_releaseTimeSum, uint new_releaseWeight, uint initialInput_ETH){ uint output_ETH = getEtherForBonds(bondsReleased); uint input_ETH = avgFactor_ethSpent[addr] * bondsReleased / hodlBonds[addr]; // hodl multiplier. because if you don't hodl at all, you shouldn't be rewarded resolves. // and the multiplier you get for hodling needs to be relative to the average hodl uint buyInTime = avgFactor_buyInTimeSum[addr] / avgFactor_ethSpent[addr]; uint cashoutTime = NOW()*scaleFactor - buyInTime; uint releaseTimeSum = avgFactor_releaseTimeSum + cashoutTime*input_ETH/scaleFactor/*to give new life more weight--->*/*buyInTime; uint releaseWeight = avgFactor_releaseWeight + input_ETH/*to give new life more weight--->*/*buyInTime/scaleFactor; uint avgCashoutTime = releaseTimeSum/releaseWeight; return (output_ETH, input_ETH * cashoutTime / avgCashoutTime * input_ETH / output_ETH, releaseTimeSum, releaseWeight, input_ETH); } event Sell( address indexed addr, uint256 bondsSold, uint256 cashout, uint256 resolves, uint256 resolveTax, uint256 initialCash); function sell(uint256 amount) internal returns(uint eth, uint resolves){ // Calculate the amount of Ether & Resolves that the holder's bonds sell for at the current sell price. uint numEthersBeforeFee; uint mintedResolves; uint releaseTimeSum; uint releaseWeight; uint initialInput_ETH; (numEthersBeforeFee,mintedResolves,releaseTimeSum,releaseWeight,initialInput_ETH) = getReturnsForBonds(msg.sender, amount); // magic distribution resolveToken.mint(msg.sender, mintedResolves); // update weighted average cashout time avgFactor_releaseTimeSum = releaseTimeSum; avgFactor_releaseWeight = releaseWeight; // reduce the amount of "eth spent" based on the percentage of bonds being sold back into the contract avgFactor_ethSpent[msg.sender] -= initialInput_ETH; // reduce the "buyInTime" sum that's used for average buy in time avgFactor_buyInTimeSum[msg.sender] = avgFactor_buyInTimeSum[msg.sender] * (hodlBonds[msg.sender] - amount) / hodlBonds[msg.sender]; // calculate the fee uint fee = fluxFee(numEthersBeforeFee); // Net Ether for the seller after the fee has been subtracted. uint numEthers = numEthersBeforeFee - fee; //updating the numerator of the fee-easing factor sellSum += initialInput_ETH; // Burn the bonds which were just sold from the total supply. _totalSupply -= amount; // Remove the bonds from the balance of the buyer. hodlBonds[msg.sender] -= amount; // Check if we have bonds in existence uint resolveFee; if (_totalSupply > 0 && dissolvingResolves > 0){ // Scale the Ether taken as the selling fee by the scaleFactor variable. resolveFee = fee * scaleFactor; // Fee is distributed to all remaining resolve holders. // rewardPerResolve is the amount gained per resolve thanks to this sell. uint rewardPerResolve = dividendDivide(resolveFee); // The Ether value per resolve is increased proportionally. earningsPerResolve += rewardPerResolve; } // Send the ethereum to the address that requested the sell. reserves -= numEthers; msg.sender.transfer(numEthers); emit Sell( msg.sender, amount, numEthers, mintedResolves, resolveFee, initialInput_ETH); return (numEthers, mintedResolves); } // Dynamic value of Ether in reserve, according to the CRR requirement. function reserve() internal view returns (uint256 amount) { return SafeMath.sub(reserves - msg.value, (uint256) ((int256) (earningsPerResolve * dissolvingResolves) - totalPayouts) / scaleFactor ); } // Calculates the number of bonds that can be bought for a given amount of Ether, according to the // dynamic reserve and _totalSupply values (derived from the buy and sell prices). function getBondsForEther(uint256 ethervalue) public view returns (uint256 bonds) { return SafeMath.sub(fixedExp( fixedLog( reserve() + ethervalue ) * crr_n/crr_d + price_coeff ) , _totalSupply); } // Semantically similar to getBondsForEther, but subtracts the callers balance from the amount of Ether returned for conversion. function calculateBondsFromReinvest(uint256 ethervalue, uint256 subvalue) public view returns (uint256 bondTokens) { return SafeMath.sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff) , _totalSupply); } // Converts a number bonds into an Ether value. function getEtherForBonds(uint256 bondTokens) public view returns (uint256 ethervalue) { // How much reserve Ether do we have left in the contract? uint reserveAmount = reserve(); // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. if (bondTokens == _totalSupply) return reserveAmount; // If there would be excess Ether left after the transaction this is called within, return the Ether // corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator // and denominator altered to 1 and 2 respectively. uint x = fixedExp( (fixedLog(_totalSupply-bondTokens)-price_coeff) * crr_d/crr_n); return SafeMath.sub(reserveAmount, x); } // You don't care about these, but if you really do they're hex values for // co-efficients used to simulate approximations of the log and exp functions. int256 constant one = 0x10000000000000000; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); int z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) function fixedExp(int256 a) internal pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } // This allows you to buy bonds by sending Ether directly to the smart contract // without including any transaction data (useful for, say, mobile wallet apps). function () payable external { // msg.value is the amount of Ether sent by the transaction. if (msg.value > 0) { fund(); } else { withdraw( resolveEarnings(msg.sender) ); } } // Allow contract to accept resolve tokens event StakeResolves( address indexed addr, uint256 amountStaked, bytes _data ); function tokenFallback(address from, uint value, bytes calldata _data) external{ if(msg.sender == address(resolveToken) ){ resolveWeight[from] += value; dissolvingResolves += value; // Update the payout array so that the "resolve shareholder" cannot claim resolveEarnings on previous staked resolves. int payoutDiff = (int256) (earningsPerResolve * value); // Then we update the payouts array for the "resolve shareholder" with this amount payouts[from] += payoutDiff; emit StakeResolves(from, value, _data); }else{ revert("no want"); } } // Withdraws resolveEarnings held by the caller sending the transaction, updates // the requisite global variables, and transfers Ether back to the caller. event Withdraw( address indexed addr, uint256 earnings, uint256 dissolve ); function withdraw(uint amount) public returns(uint){ // Retrieve the resolveEarnings associated with the address the request came from. uint totalEarnings = resolveEarnings(msg.sender); require(amount <= totalEarnings, "the amount exceeds total earnings"); uint oldWeight = resolveWeight[msg.sender]; resolveWeight[msg.sender] = oldWeight * (totalEarnings - amount) / totalEarnings; uint weightDiff = oldWeight - resolveWeight[msg.sender]; dissolved += weightDiff; dissolvingResolves -= weightDiff; //something about invariance int resolvePayoutDiff = (int256) (earningsPerResolve * weightDiff); payouts[msg.sender] += resolvePayoutDiff; // Increase the total amount that's been paid out to maintain invariance. totalPayouts += resolvePayoutDiff; // Send the resolveEarnings to the address that requested the withdraw. msg.sender.transfer(amount); emit Withdraw( msg.sender, amount, weightDiff); return weightDiff; } event PullResolves( address indexed addr, uint256 pulledResolves, uint256 forfeiture); function pullResolves(uint amount) public{ require(amount <= resolveWeight[msg.sender], "that amount is too large"); require(amount != dissolvingResolves, "you can't forfeit the last amount"); //something about invariance uint forfeitedEarnings = amount * earningsPerResolve; // Update the payout array so that the "resolve shareholder" cannot claim resolveEarnings on previous staked resolves. // Then we update the payouts array for the "resolve shareholder" with this amount payouts[msg.sender] -= (int256) (earningsPerResolve * amount); resolveWeight[msg.sender] -= amount; dissolvingResolves -= amount; // The Ether value per token is increased proportionally. earningsPerResolve += dividendDivide( forfeitedEarnings ); resolveToken.transfer(msg.sender, amount); emit PullResolves( msg.sender, amount, forfeitedEarnings / scaleFactor); } event BondTransfer(address from, address to, uint amount); function bondTransfer( address to, uint amount ) public{ //attack someone's resolve potential by sending them some love address sender = msg.sender; uint totalBonds = hodlBonds[sender]; require(amount <= totalBonds, "amount exceeds hodlBonds"); uint ethSpent = avgFactor_ethSpent[sender] * amount / totalBonds; uint buyInTimeSum = avgFactor_buyInTimeSum[sender] * amount / totalBonds; avgFactor_ethSpent[sender] -= ethSpent; avgFactor_buyInTimeSum[sender] -= buyInTimeSum; hodlBonds[sender] -= amount; avgFactor_ethSpent[to] += ethSpent; avgFactor_buyInTimeSum[to] += buyInTimeSum; hodlBonds[to] += amount; emit BondTransfer(sender, to, amount); } } contract ERC223ReceivingContract{ function tokenFallback(address _from, uint _value, bytes calldata _data) external; } contract ResolveToken{ address pyramid; constructor(address _pyramid) public{ pyramid = _pyramid; } modifier pyramidOnly{ require(msg.sender == pyramid); _; } event Transfer( address indexed from, address indexed to, uint256 amount, bytes data ); event Mint( address indexed addr, uint256 amount ); mapping(address => uint) balances; mapping(address => mapping(address => uint)) approvals; string public name = "Resolve"; string public symbol = "PoWHr"; uint8 constant public decimals = 18; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function mint(address _address, uint _value) public pyramidOnly(){ balances[_address] += _value; _totalSupply += _value; emit Mint(_address, _value); } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes memory _data) public returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); if(isContract(_to)) { return transferToContract(_to, _value, _data); }else{ return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) public returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)){ return transferToContract(_to, _value, empty); }else{ return transferToAddress(_to, _value, empty); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) public view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } if(length>0) { return true; }else { return false; } } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes memory _data) private returns (bool success) { moveTokens(msg.sender,_to,_value); emit Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes memory _data) private returns (bool success) { moveTokens(msg.sender, _to, _value); ERC223ReceivingContract reciever = ERC223ReceivingContract(_to); reciever.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; } function moveTokens(address _from, address _to, uint _amount) private{ balances[_from] -= _amount; balances[_to] += _amount; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } function allowance(address src, address guy) public view returns (uint) { return approvals[src][guy]; } function transferFrom(address src, address dst, uint wad) public returns (bool){ require(approvals[src][msg.sender] >= wad, "That amount is not approved"); require(balances[src] >= wad, "That amount is not available from this wallet"); if (src != msg.sender) { approvals[src][msg.sender] -= wad; } moveTokens(src,dst,wad); bytes memory empty; emit Transfer(src, dst, wad, empty); return true; } function approve(address guy, uint wad) public returns (bool) { approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } event Approval(address indexed src, address indexed guy, uint wad); } /** * @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; } }
This allows you to buy bonds by sending Ether directly to the smart contract without including any transaction data (useful for, say, mobile wallet apps). msg.value is the amount of Ether sent by the transaction.
function () payable external { if (msg.value > 0) { fund(); withdraw( resolveEarnings(msg.sender) ); } }
12,792,472
./full_match/84531/0xaBf20d6c101bd3DD955902056a4aE277faf8d62f/sources/project:/contracts/seedify-fund.sol
========== OWNER FUNCTION ========== /
function setTiers(uint256[] calldata minCaps, uint256[] calldata maxCaps) public onlyOwner { require(minCaps.length == 6, "array lenth must eval to 6"); require(minCaps.length == maxCaps.length, "maxCaps and minCaps must have a same length"); for (uint i = 0; i < 6; i++) { tierDetail[i + 1] = Tier( minCaps[i].mul(exchangeRate), maxCaps[i].mul(exchangeRate) ); } }
11,502,026
./full_match/1/0xF5abAdec1bcb7d79D0E972981F13D731D5d06aA8/sources/contracts/loyalty/GenArtLoyaltyVault.sol
Update reward for a user account _user address of the user/
function _updateReward(address _user) internal { if (block.number != lastUpdateBlock) { rewardPerTokenStored = _rewardPerShare(); lastUpdateBlock = _lastRewardBlock(); } userInfo[_user].rewards = _calculatePendingRewards(_user); userInfo[_user].userRewardPerTokenPaid = rewardPerTokenStored; }
4,883,610
./full_match/11155111/0x5d258eb7400E468239Da08A0965e5be182445170/sources/contracts/Nevo.sol
Store the minter's address
function mint(string memory name, address user, string memory tokenURI) public payable returns (uint256) { uint256 tokenId = _tokenIds.current(); _mint(user, tokenId); _setTokenURI(tokenId, tokenURI); tokenNames[tokenId] = name; _tokenIds.increment(); payable(feeAddress).transfer(0.1 ether); minters[tokenId] = msg.sender; return tokenId; }
3,786,722
/** *Submitted for verification at Etherscan.io on 2021-02-12 */ pragma solidity 0.8.0; pragma abicoder v2; interface MassetStructs { struct BassetPersonal { // Address of the bAsset address addr; // Address of the bAsset address integrator; // An ERC20 can charge transfer fee, for example USDT, DGX tokens. bool hasTxFee; // takes a byte in storage // Status of the bAsset BassetStatus status; } struct BassetData { // 1 Basset * ratio / ratioScale == x Masset (relative value) // If ratio == 10e8 then 1 bAsset = 10 mAssets // A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) uint128 ratio; // Amount of the Basset that is held in Collateral uint128 vaultBalance; } // Status of the Basset - has it broken its peg? enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } struct BasketState { bool undergoingRecol; bool failed; } struct InvariantConfig { uint256 a; WeightLimits limits; } struct WeightLimits { uint128 min; uint128 max; } struct AmpData { uint64 initialA; uint64 targetA; uint64 rampStartTime; uint64 rampEndTime; } } abstract contract IInvariantValidator is MassetStructs { // Mint function computeMint( BassetData[] calldata _bAssets, uint8 _i, uint256 _rawInput, InvariantConfig memory _config ) external view virtual returns (uint256); function computeMintMulti( BassetData[] calldata _bAssets, uint8[] calldata _indices, uint256[] calldata _rawInputs, InvariantConfig memory _config ) external view virtual returns (uint256); // Swap function computeSwap( BassetData[] calldata _bAssets, uint8 _i, uint8 _o, uint256 _rawInput, uint256 _feeRate, InvariantConfig memory _config ) external view virtual returns (uint256, uint256); // Redeem function computeRedeem( BassetData[] calldata _bAssets, uint8 _i, uint256 _mAssetQuantity, InvariantConfig memory _config ) external view virtual returns (uint256); function computeRedeemExact( BassetData[] calldata _bAssets, uint8[] calldata _indices, uint256[] calldata _rawOutputs, InvariantConfig memory _config ) external view virtual returns (uint256); } contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: AGPL-3.0-or-later /* * @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 { // 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 payable(msg.sender); } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC205 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - 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 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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] -= 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 { require(account != address(0), "ERC20: mint to the zero address"); _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 { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()] - amount); } } abstract contract InitializableERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } abstract contract InitializableToken is ERC205, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } contract InitializableReentrancyGuard { bool private _notEntered; function _initializeReentrancyGuard() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _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; } } abstract contract IMasset is MassetStructs { // Mint function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function mintMulti( address[] calldata _inputs, uint256[] calldata _inputQuantities, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function getMintOutput(address _input, uint256 _inputQuantity) external view virtual returns (uint256 mintOutput); function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view virtual returns (uint256 mintOutput); // Swaps function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 swapOutput); function getSwapOutput( address _input, address _output, uint256 _inputQuantity ) external view virtual returns (uint256 swapOutput); // Redemption function redeem( address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 outputQuantity); function redeemMasset( uint256 _mAssetQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) external virtual returns (uint256[] memory outputQuantities); function redeemExactBassets( address[] calldata _outputs, uint256[] calldata _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) external virtual returns (uint256 mAssetRedeemed); function getRedeemOutput(address _output, uint256 _mAssetQuantity) external view virtual returns (uint256 bAssetOutput); function getRedeemExactBassetsOutput( address[] calldata _outputs, uint256[] calldata _outputQuantities ) external view virtual returns (uint256 mAssetAmount); // Views function getBasket() external view virtual returns (bool, bool); function getBasset(address _token) external view virtual returns (BassetPersonal memory personal, BassetData memory data); function getBassets() external view virtual returns (BassetPersonal[] memory personal, BassetData[] memory data); function bAssetIndexes(address) external view virtual returns (uint8); // SavingsManager function collectInterest() external virtual returns (uint256 swapFeesGained, uint256 newSupply); function collectPlatformInterest() external virtual returns (uint256 mintAmount, uint256 newSupply); // Admin function setCacheSize(uint256 _cacheSize) external virtual; function upgradeForgeValidator(address _newForgeValidator) external virtual; function setFees(uint256 _swapFee, uint256 _redemptionFee) external virtual; function setTransferFeesFlag(address _bAsset, bool _flag) external virtual; function migrateBassets(address[] calldata _bAssets, address _newIntegration) external virtual; } abstract contract Deprecated_BasketManager is MassetStructs {} library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } library StableMath { /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x * FULL_SCALE; } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 // return 9e38 / 1e18 = 9e18 return (x * y) / scale; } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x * y; // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled + FULL_SCALE - 1; // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil / FULL_SCALE; } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 // e.g. 8e36 / 10e18 = 8e17 return (x * FULL_SCALE) / y; } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return c Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x * ratio; // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled + RATIO_SCALE - 1; // return 100..00.999e8 / 1e8 = 1e18 return ceil / RATIO_SCALE; } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return c Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 // return 1e22 / 1e12 = 1e10 return (x * RATIO_SCALE) / ratio; } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } } interface IPlatformIntegration { /** * @dev Deposit the given bAsset to Lending platform * @param _bAsset bAsset address * @param _amount Amount to deposit */ function deposit( address _bAsset, uint256 _amount, bool isTokenFeeCharged ) external returns (uint256 quantityDeposited); /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from the cache */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external; /** * @dev Returns the current balance of the given bAsset */ function checkBalance(address _bAsset) external returns (uint256 balance); /** * @dev Returns the pToken */ function bAssetToPToken(address _bAsset) external returns (address pToken); } interface IBasicToken { function decimals() external view returns (uint8); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ /** * @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.3._ */ 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.3._ */ 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); } } } } 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 { uint256 newAllowance = token.allowance(address(this), spender) - 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"); } } } library MassetHelpers { using SafeERC20 for IERC20; function transferReturnBalance( address _sender, address _recipient, address _bAsset, uint256 _qty ) internal returns (uint256 receivedQty, uint256 recipientBalance) { uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient); IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty); recipientBalance = IERC20(_bAsset).balanceOf(_recipient); receivedQty = recipientBalance - balBefore; } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, 2**256 - 1); } } library Manager { using SafeERC20 for IERC20; using StableMath for uint256; event BassetsMigrated(address[] bAssets, address newIntegrator); event TransferFeeEnabled(address indexed bAsset, bool enabled); event BassetAdded(address indexed bAsset, address integrator); event BassetStatusChanged(address indexed bAsset, MassetStructs.BassetStatus status); event BasketStatusChanged(); event StartRampA(uint256 currentA, uint256 targetA, uint256 startTime, uint256 rampEndTime); event StopRampA(uint256 currentA, uint256 time); uint256 private constant MIN_RAMP_TIME = 1 days; uint256 private constant MAX_A = 1e6; /** * @notice Adds a bAsset to the given personal, data and mapping, provided it is valid * @param _bAssetPersonal Basset data storage array * @param _bAssetData Basset data storage array * @param _bAssetIndexes Mapping of bAsset address to their index * @param _maxBassets Max size of the basket * @param _bAsset Address of the ERC20 token to add to the Basket * @param _integration Address of the Platform Integration * @param _mm Base 1e8 var to determine measurement ratio * @param _hasTxFee Are transfer fees charged on this bAsset (e.g. USDT) */ function addBasset( MassetStructs.BassetPersonal[] storage _bAssetPersonal, MassetStructs.BassetData[] storage _bAssetData, mapping(address => uint8) storage _bAssetIndexes, uint8 _maxBassets, address _bAsset, address _integration, uint256 _mm, bool _hasTxFee ) external { require(_bAsset != address(0), "bAsset address must be valid"); uint8 bAssetCount = uint8(_bAssetPersonal.length); require(bAssetCount < _maxBassets, "Max bAssets in Basket"); uint8 idx = _bAssetIndexes[_bAsset]; require( bAssetCount == 0 || _bAssetPersonal[idx].addr != _bAsset, "bAsset already exists in Basket" ); // Should fail if bAsset is not added to integration // Programmatic enforcement of bAsset validity should service through decentralised feed if (_integration != address(0)) { IPlatformIntegration(_integration).checkBalance(_bAsset); } uint256 bAssetDecimals = IBasicToken(_bAsset).decimals(); require( bAssetDecimals >= 4 && bAssetDecimals <= 18, "Token must have sufficient decimal places" ); uint256 delta = uint256(18) - bAssetDecimals; uint256 ratio = _mm * (10**delta); _bAssetIndexes[_bAsset] = bAssetCount; _bAssetPersonal.push( MassetStructs.BassetPersonal({ addr: _bAsset, integrator: _integration, hasTxFee: _hasTxFee, status: MassetStructs.BassetStatus.Normal }) ); _bAssetData.push( MassetStructs.BassetData({ ratio: SafeCast.toUint128(ratio), vaultBalance: 0 }) ); emit BassetAdded(_bAsset, _integration); } /** * @dev Collects the interest generated from the Basket, minting a relative * amount of mAsset and sending it over to the SavingsManager. * @param _bAssetPersonal Basset personal storage array * @param _bAssetData Basset data storage array * @param _forgeValidator Link to the current InvariantValidator * @return mintAmount Lending market interest collected * @return rawGains Raw increases in vault Balance */ function collectPlatformInterest( MassetStructs.BassetPersonal[] memory _bAssetPersonal, MassetStructs.BassetData[] storage _bAssetData, IInvariantValidator _forgeValidator, MassetStructs.InvariantConfig memory _config ) external returns (uint256 mintAmount, uint256[] memory rawGains) { // Get basket details MassetStructs.BassetData[] memory bAssetData_ = _bAssetData; uint256 count = bAssetData_.length; uint8[] memory indices = new uint8[](count); rawGains = new uint256[](count); // 1. Calculate rawGains in each bAsset, in comparison to current vault balance for (uint256 i = 0; i < count; i++) { indices[i] = uint8(i); MassetStructs.BassetPersonal memory bPersonal = _bAssetPersonal[i]; MassetStructs.BassetData memory bData = bAssetData_[i]; // If there is no integration, then nothing can have accrued if (bPersonal.integrator == address(0)) continue; uint256 lending = IPlatformIntegration(bPersonal.integrator).checkBalance(bPersonal.addr); uint256 cache = 0; if (!bPersonal.hasTxFee) { cache = IERC20(bPersonal.addr).balanceOf(bPersonal.integrator); } uint256 balance = lending + cache; uint256 oldVaultBalance = bData.vaultBalance; if ( balance > oldVaultBalance && bPersonal.status == MassetStructs.BassetStatus.Normal ) { _bAssetData[i].vaultBalance = SafeCast.toUint128(balance); uint256 interestDelta = balance - oldVaultBalance; rawGains[i] = interestDelta; } else { rawGains[i] = 0; } } mintAmount = _forgeValidator.computeMintMulti(bAssetData_, indices, rawGains, _config); } /** * @dev Update transfer fee flag for a given bAsset, should it change its fee practice * @param _bAssetPersonal Basset data storage array * @param _bAssetIndexes Mapping of bAsset address to their index * @param _bAsset bAsset address * @param _flag Charge transfer fee when its set to 'true', otherwise 'false' */ function setTransferFeesFlag( MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset, bool _flag ) external { uint256 index = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, _bAsset); _bAssetPersonal[index].hasTxFee = _flag; if (_flag) { // if token has tx fees, it can no longer operate with a cache address integration = _bAssetPersonal[index].integrator; if (integration != address(0)) { uint256 bal = IERC20(_bAsset).balanceOf(integration); if (bal > 0) { IPlatformIntegration(integration).deposit(_bAsset, bal, true); } } } emit TransferFeeEnabled(_bAsset, _flag); } /** * @dev Transfers all collateral from one lending market to another - used initially * to handle the migration between Aave V1 and Aave V2. Note - only supports non * tx fee enabled assets. Supports going from no integration to integration, but * not the other way around. * @param _bAssetPersonal Basset data storage array * @param _bAssetIndexes Mapping of bAsset address to their index * @param _bAssets Array of basket assets to migrate * @param _newIntegration Address of the new platform integration */ function migrateBassets( MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address[] calldata _bAssets, address _newIntegration ) external { uint256 len = _bAssets.length; require(len > 0, "Must migrate some bAssets"); for (uint256 i = 0; i < len; i++) { // 1. Check that the bAsset is in the basket address bAsset = _bAssets[i]; uint256 index = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, bAsset); require(!_bAssetPersonal[index].hasTxFee, "A bAsset has a transfer fee"); // 2. Withdraw everything from the old platform integration address oldAddress = _bAssetPersonal[index].integrator; require(oldAddress != _newIntegration, "Must transfer to new integrator"); (uint256 cache, uint256 lendingBal) = (0, 0); if (oldAddress == address(0)) { cache = IERC20(bAsset).balanceOf(address(this)); } else { IPlatformIntegration oldIntegration = IPlatformIntegration(oldAddress); cache = IERC20(bAsset).balanceOf(address(oldIntegration)); // 2.1. Withdraw from the lending market lendingBal = oldIntegration.checkBalance(bAsset); if (lendingBal > 0) { oldIntegration.withdraw(address(this), bAsset, lendingBal, false); } // 2.2. Withdraw from the cache, if any if (cache > 0) { oldIntegration.withdrawRaw(address(this), bAsset, cache); } } uint256 sum = lendingBal + cache; // 3. Update the integration address for this bAsset _bAssetPersonal[index].integrator = _newIntegration; // 4. Deposit everything into the new // This should fail if we did not receive the full amount from the platform withdrawal // 4.1. Deposit all bAsset IERC20(bAsset).safeTransfer(_newIntegration, sum); IPlatformIntegration newIntegration = IPlatformIntegration(_newIntegration); if (lendingBal > 0) { newIntegration.deposit(bAsset, lendingBal, false); } // 4.2. Check balances uint256 newLendingBal = newIntegration.checkBalance(bAsset); uint256 newCache = IERC20(bAsset).balanceOf(address(newIntegration)); uint256 upperMargin = 10001e14; uint256 lowerMargin = 9999e14; require( newLendingBal >= lendingBal.mulTruncate(lowerMargin) && newLendingBal <= lendingBal.mulTruncate(upperMargin), "Must transfer full amount" ); require( newCache >= cache.mulTruncate(lowerMargin) && newCache <= cache.mulTruncate(upperMargin), "Must transfer full amount" ); } emit BassetsMigrated(_bAssets, _newIntegration); } /** * @dev Executes the Auto Redistribution event by isolating the bAsset from the Basket * @param _basket Struct containing core basket info * @param _bAssetPersonal Basset data storage array * @param _bAsset Address of the ERC20 token to isolate * @param _belowPeg Bool to describe whether the bAsset deviated below peg (t) * or above (f) */ function handlePegLoss( MassetStructs.BasketState storage _basket, MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset, bool _belowPeg ) external { require(!_basket.failed, "Basket must be alive"); uint256 i = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, _bAsset); MassetStructs.BassetStatus newStatus = _belowPeg ? MassetStructs.BassetStatus.BrokenBelowPeg : MassetStructs.BassetStatus.BrokenAbovePeg; _bAssetPersonal[i].status = newStatus; _basket.undergoingRecol = true; emit BassetStatusChanged(_bAsset, newStatus); } /** * @dev Negates the isolation of a given bAsset * @param _basket Struct containing core basket info * @param _bAssetPersonal Basset data storage array * @param _bAssetIndexes Mapping of bAsset address to their index * @param _bAsset Address of the bAsset */ function negateIsolation( MassetStructs.BasketState storage _basket, MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _bAsset ) external { uint256 i = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, _bAsset); _bAssetPersonal[i].status = MassetStructs.BassetStatus.Normal; bool undergoingRecol = false; for (uint256 j = 0; j < _bAssetPersonal.length; j++) { if (_bAssetPersonal[j].status != MassetStructs.BassetStatus.Normal) { undergoingRecol = true; break; } } _basket.undergoingRecol = undergoingRecol; emit BassetStatusChanged(_bAsset, MassetStructs.BassetStatus.Normal); } /** * @dev Starts changing of the amplification var A * @param _targetA Target A value * @param _rampEndTime Time at which A will arrive at _targetA */ function startRampA( MassetStructs.AmpData storage _ampData, uint256 _targetA, uint256 _rampEndTime, uint256 _currentA, uint256 _precision ) external { require( block.timestamp >= (_ampData.rampStartTime + MIN_RAMP_TIME), "Sufficient period of previous ramp has not elapsed" ); require(_rampEndTime >= (block.timestamp + MIN_RAMP_TIME), "Ramp time too short"); require(_targetA > 0 && _targetA < MAX_A, "A target out of bounds"); uint256 preciseTargetA = _targetA * _precision; if (preciseTargetA > _currentA) { require(preciseTargetA <= _currentA * 10, "A target increase too big"); } else { require(preciseTargetA >= _currentA / 10, "A target decrease too big"); } _ampData.initialA = SafeCast.toUint64(_currentA); _ampData.targetA = SafeCast.toUint64(preciseTargetA); _ampData.rampStartTime = SafeCast.toUint64(block.timestamp); _ampData.rampEndTime = SafeCast.toUint64(_rampEndTime); emit StartRampA(_currentA, preciseTargetA, block.timestamp, _rampEndTime); } /** * @dev Stops the changing of the amplification var A, setting * it to whatever the current value is. */ function stopRampA(MassetStructs.AmpData storage _ampData, uint256 _currentA) external { require(block.timestamp < _ampData.rampEndTime, "Amplification not changing"); _ampData.initialA = SafeCast.toUint64(_currentA); _ampData.targetA = SafeCast.toUint64(_currentA); _ampData.rampStartTime = SafeCast.toUint64(block.timestamp); _ampData.rampEndTime = SafeCast.toUint64(block.timestamp); emit StopRampA(_currentA, block.timestamp); } /** * @dev Gets a bAsset index from storage * @param _asset Address of the asset * @return idx Index of the asset */ function _getAssetIndex( MassetStructs.BassetPersonal[] storage _bAssetPersonal, mapping(address => uint8) storage _bAssetIndexes, address _asset ) internal view returns (uint8 idx) { idx = _bAssetIndexes[_asset]; require(_bAssetPersonal[idx].addr == _asset, "Invalid asset input"); } /*************************************** FORGING ****************************************/ /** * @dev Deposits a given asset to the system. If there is sufficient room for the asset * in the cache, then just transfer, otherwise reset the cache to the desired mid level by * depositing the delta in the platform */ function depositTokens( MassetStructs.BassetPersonal memory _bAsset, uint256 _bAssetRatio, uint256 _quantity, uint256 _maxCache ) external returns (uint256 quantityDeposited) { // 0. If integration is 0, short circuit if (_bAsset.integrator == address(0)) { (uint256 received, ) = MassetHelpers.transferReturnBalance( msg.sender, address(this), _bAsset.addr, _quantity ); return received; } // 1 - Send all to PI, using the opportunity to get the cache balance and net amount transferred uint256 cacheBal; (quantityDeposited, cacheBal) = MassetHelpers.transferReturnBalance( msg.sender, _bAsset.integrator, _bAsset.addr, _quantity ); // 2 - Deposit X if necessary // 2.1 - Deposit if xfer fees if (_bAsset.hasTxFee) { uint256 deposited = IPlatformIntegration(_bAsset.integrator).deposit( _bAsset.addr, quantityDeposited, true ); return StableMath.min(deposited, quantityDeposited); } // 2.2 - Else Deposit X if Cache > % // This check is in place to ensure that any token with a txFee is rejected require(quantityDeposited == _quantity, "Asset not fully transferred"); uint256 relativeMaxCache = _maxCache.divRatioPrecisely(_bAssetRatio); if (cacheBal > relativeMaxCache) { uint256 delta = cacheBal - (relativeMaxCache / 2); IPlatformIntegration(_bAsset.integrator).deposit(_bAsset.addr, delta, false); } } /** * @dev Withdraws a given asset from its platformIntegration. If there is sufficient liquidity * in the cache, then withdraw from there, otherwise withdraw from the lending market and reset the * cache to the mid level. */ function withdrawTokens( uint256 _quantity, MassetStructs.BassetPersonal memory _personal, MassetStructs.BassetData memory _data, address _recipient, uint256 _maxCache ) external { if (_quantity == 0) return; // 1.0 If there is no integrator, send from here if (_personal.integrator == address(0)) { IERC20(_personal.addr).safeTransfer(_recipient, _quantity); } // 1.1 If txFee then short circuit - there is no cache else if (_personal.hasTxFee) { IPlatformIntegration(_personal.integrator).withdraw( _recipient, _personal.addr, _quantity, _quantity, true ); } // 1.2. Else, withdraw from either cache or main vault else { uint256 cacheBal = IERC20(_personal.addr).balanceOf(_personal.integrator); // 2.1 - If balance b in cache, simply withdraw if (cacheBal >= _quantity) { IPlatformIntegration(_personal.integrator).withdrawRaw( _recipient, _personal.addr, _quantity ); } // 2.2 - Else reset the cache to X, or as far as possible // - Withdraw X+b from platform // - Send b to user else { uint256 relativeMidCache = _maxCache.divRatioPrecisely(_data.ratio) / 2; uint256 totalWithdrawal = StableMath.min( relativeMidCache + _quantity - cacheBal, _data.vaultBalance - SafeCast.toUint128(cacheBal) ); IPlatformIntegration(_personal.integrator).withdraw( _recipient, _personal.addr, _quantity, totalWithdrawal, false ); } } } } // External // Internal // Libs /** * @title Masset * @author mStable * @notice An incentivised constant sum market maker with hard limits at max region. This supports * low slippage swaps and applies penalties towards min and max regions. AMM produces a * stablecoin (mAsset) and redirects lending market interest and swap fees to the savings * contract, producing a second yield bearing asset. * @dev VERSION: 3.0 * DATE: 2021-01-22 */ contract Masset is IMasset, Initializable, InitializableToken, ImmutableModule, InitializableReentrancyGuard { using StableMath for uint256; // Forging Events event Minted( address indexed minter, address recipient, uint256 mAssetQuantity, address input, uint256 inputQuantity ); event MintedMulti( address indexed minter, address recipient, uint256 mAssetQuantity, address[] inputs, uint256[] inputQuantities ); event Swapped( address indexed swapper, address input, address output, uint256 outputAmount, uint256 scaledFee, address recipient ); event Redeemed( address indexed redeemer, address recipient, uint256 mAssetQuantity, address output, uint256 outputQuantity, uint256 scaledFee ); event RedeemedMulti( address indexed redeemer, address recipient, uint256 mAssetQuantity, address[] outputs, uint256[] outputQuantity, uint256 scaledFee ); // State Events event CacheSizeChanged(uint256 cacheSize); event FeesChanged(uint256 swapFee, uint256 redemptionFee); event WeightLimitsChanged(uint128 min, uint128 max); event ForgeValidatorChanged(address forgeValidator); // Release 1.0 VARS IInvariantValidator public forgeValidator; bool private forgeValidatorLocked; // Deprecated - maintain for storage layout in mUSD Deprecated_BasketManager private deprecated_basketManager; // Basic redemption fee information uint256 public swapFee; uint256 private MAX_FEE; // Release 1.1 VARS uint256 public redemptionFee; // Release 2.0 VARS uint256 public cacheSize; uint256 public surplus; // Release 3.0 VARS // Struct holding Basket details BassetPersonal[] public bAssetPersonal; BassetData[] public bAssetData; mapping(address => uint8) public override bAssetIndexes; uint8 public maxBassets; BasketState public basket; // Amplification Data uint256 private constant A_PRECISION = 100; AmpData public ampData; WeightLimits public weightLimits; /** * @dev Constructor to set immutable bytecode * @param _nexus Nexus address */ constructor(address _nexus) ImmutableModule(_nexus) {} /** * @dev Initialization function for upgradable proxy contract. * This function should be called via Proxy just after contract deployment. * To avoid variable shadowing appended `Arg` after arguments name. * @param _nameArg Name of the mAsset * @param _symbolArg Symbol of the mAsset * @param _forgeValidator Address of the AMM implementation * @param _bAssets Array of Basset data */ function initialize( string calldata _nameArg, string calldata _symbolArg, address _forgeValidator, BassetPersonal[] calldata _bAssets, InvariantConfig memory _config ) public initializer { InitializableToken._initialize(_nameArg, _symbolArg); _initializeReentrancyGuard(); forgeValidator = IInvariantValidator(_forgeValidator); maxBassets = 10; uint256 len = _bAssets.length; require(len > 0, "No bAssets"); for (uint256 i = 0; i < len; i++) { Manager.addBasset( bAssetPersonal, bAssetData, bAssetIndexes, maxBassets, _bAssets[i].addr, _bAssets[i].integrator, 1e8, _bAssets[i].hasTxFee ); } uint64 startA = SafeCast.toUint64(_config.a * A_PRECISION); ampData = AmpData(startA, startA, 0, 0); weightLimits = _config.limits; MAX_FEE = 2e16; swapFee = 6e14; redemptionFee = 3e14; cacheSize = 1e17; } /** * @dev Verifies that the caller is the Savings Manager contract */ modifier onlySavingsManager() { _isSavingsManager(); _; } // Internal fn for modifier to reduce deployment size function _isSavingsManager() internal view { require(_savingsManager() == msg.sender, "Must be savings manager"); } /** * @dev Requires the overall basket composition to be healthy */ modifier whenHealthy() { _isHealthy(); _; } // Internal fn for modifier to reduce deployment size function _isHealthy() internal view { BasketState memory basket_ = basket; require(!basket_.undergoingRecol && !basket_.failed, "Unhealthy"); } /** * @dev Requires the basket not to be undergoing recollateralisation */ modifier whenNoRecol() { _noRecol(); _; } // Internal fn for modifier to reduce deployment size function _noRecol() internal view { BasketState memory basket_ = basket; require(!basket_.undergoingRecol, "In recol"); } /*************************************** MINTING (PUBLIC) ****************************************/ /** * @dev Mint a single bAsset, at a 1:1 ratio with the bAsset. This contract * must have approval to spend the senders bAsset * @param _input Address of the bAsset to deposit for the minted mAsset. * @param _inputQuantity Quantity in bAsset units * @param _minOutputQuantity Minimum mAsset quanity to be minted. This protects against slippage. * @param _recipient Receipient of the newly minted mAsset tokens * @return mintOutput Quantity of newly minted mAssets for the deposited bAsset. */ function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external override nonReentrant whenHealthy returns (uint256 mintOutput) { mintOutput = _mintTo(_input, _inputQuantity, _minOutputQuantity, _recipient); } /** * @dev Mint with multiple bAssets, at a 1:1 ratio to mAsset. This contract * must have approval to spend the senders bAssets * @param _inputs Non-duplicate address array of bASset addresses to deposit for the minted mAsset tokens. * @param _inputQuantities Quantity of each bAsset to deposit for the minted mAsset. * Order of array should mirror the above bAsset addresses. * @param _minOutputQuantity Minimum mAsset quanity to be minted. This protects against slippage. * @param _recipient Address to receive the newly minted mAsset tokens * @return mintOutput Quantity of newly minted mAssets for the deposited bAssets. */ function mintMulti( address[] calldata _inputs, uint256[] calldata _inputQuantities, uint256 _minOutputQuantity, address _recipient ) external override nonReentrant whenHealthy returns (uint256 mintOutput) { mintOutput = _mintMulti(_inputs, _inputQuantities, _minOutputQuantity, _recipient); } /** * @dev Get the projected output of a given mint * @param _input Address of the bAsset to deposit for the minted mAsset * @param _inputQuantity Quantity in bAsset units * @return mintOutput Estimated mint output in mAsset terms */ function getMintOutput(address _input, uint256 _inputQuantity) external view override returns (uint256 mintOutput) { require(_inputQuantity > 0, "Qty==0"); (uint8 idx, ) = _getAsset(_input); mintOutput = forgeValidator.computeMint(bAssetData, idx, _inputQuantity, _getConfig()); } /** * @dev Get the projected output of a given mint * @param _inputs Non-duplicate address array of addresses to bAssets to deposit for the minted mAsset tokens. * @param _inputQuantities Quantity of each bAsset to deposit for the minted mAsset. * @return mintOutput Estimated mint output in mAsset terms */ function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view override returns (uint256 mintOutput) { uint256 len = _inputQuantities.length; require(len > 0 && len == _inputs.length, "Input array mismatch"); (uint8[] memory indexes, ) = _getBassets(_inputs); return forgeValidator.computeMintMulti(bAssetData, indexes, _inputQuantities, _getConfig()); } /*************************************** MINTING (INTERNAL) ****************************************/ /** @dev Mint Single */ function _mintTo( address _input, uint256 _inputQuantity, uint256 _minMassetQuantity, address _recipient ) internal returns (uint256 mAssetMinted) { require(_recipient != address(0), "Invalid recipient"); require(_inputQuantity > 0, "Qty==0"); BassetData[] memory allBassets = bAssetData; (uint8 bAssetIndex, BassetPersonal memory personal) = _getAsset(_input); Cache memory cache = _getCacheDetails(); // Transfer collateral to the platform integration address and call deposit uint256 quantityDeposited = Manager.depositTokens( personal, allBassets[bAssetIndex].ratio, _inputQuantity, cache.maxCache ); // Validation should be after token transfer, as bAssetQty is unknown before mAssetMinted = forgeValidator.computeMint( allBassets, bAssetIndex, quantityDeposited, _getConfig() ); require(mAssetMinted >= _minMassetQuantity, "Mint quantity < min qty"); // Log the Vault increase - can only be done when basket is healthy bAssetData[bAssetIndex].vaultBalance = allBassets[bAssetIndex].vaultBalance + SafeCast.toUint128(quantityDeposited); // Mint the Masset _mint(_recipient, mAssetMinted); emit Minted(msg.sender, _recipient, mAssetMinted, _input, quantityDeposited); } /** @dev Mint Multi */ function _mintMulti( address[] memory _inputs, uint256[] memory _inputQuantities, uint256 _minMassetQuantity, address _recipient ) internal returns (uint256 mAssetMinted) { require(_recipient != address(0), "Invalid recipient"); uint256 len = _inputQuantities.length; require(len > 0 && len == _inputs.length, "Input array mismatch"); // Load bAssets from storage into memory (uint8[] memory indexes, BassetPersonal[] memory personals) = _getBassets(_inputs); BassetData[] memory allBassets = bAssetData; Cache memory cache = _getCacheDetails(); uint256[] memory quantitiesDeposited = new uint256[](len); // Transfer the Bassets to the integrator, update storage and calc MassetQ for (uint256 i = 0; i < len; i++) { uint256 bAssetQuantity = _inputQuantities[i]; if (bAssetQuantity > 0) { uint8 idx = indexes[i]; BassetData memory data = allBassets[idx]; BassetPersonal memory personal = personals[i]; uint256 quantityDeposited = Manager.depositTokens(personal, data.ratio, bAssetQuantity, cache.maxCache); quantitiesDeposited[i] = quantityDeposited; bAssetData[idx].vaultBalance = data.vaultBalance + SafeCast.toUint128(quantityDeposited); } } // Validate the proposed mint, after token transfer mAssetMinted = forgeValidator.computeMintMulti( allBassets, indexes, quantitiesDeposited, _getConfig() ); require(mAssetMinted >= _minMassetQuantity, "Mint quantity < min qty"); require(mAssetMinted > 0, "Zero mAsset quantity"); // Mint the Masset _mint(_recipient, mAssetMinted); emit MintedMulti(msg.sender, _recipient, mAssetMinted, _inputs, _inputQuantities); } /*************************************** SWAP (PUBLIC) ****************************************/ /** * @dev Swaps one bAsset for another bAsset using the bAsset addresses. * bAsset <> bAsset swaps will incur a small fee (swapFee()). * @param _input Address of bAsset to deposit * @param _output Address of bAsset to receive * @param _inputQuantity Units of input bAsset to swap * @param _minOutputQuantity Minimum quantity of the swap output asset. This protects against slippage * @param _recipient Address to transfer output asset to * @return swapOutput Quantity of output asset returned from swap */ function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external override nonReentrant whenHealthy returns (uint256 swapOutput) { swapOutput = _swap(_input, _output, _inputQuantity, _minOutputQuantity, _recipient); } /** * @dev Determines both if a trade is valid, and the expected fee or output. * Swap is valid if it does not result in the input asset exceeding its maximum weight. * @param _input Address of bAsset to deposit * @param _output Address of bAsset to receive * @param _inputQuantity Units of input bAsset to swap * @return swapOutput Quantity of output asset returned from swap */ function getSwapOutput( address _input, address _output, uint256 _inputQuantity ) external view override returns (uint256 swapOutput) { require(_input != _output, "Invalid pair"); require(_inputQuantity > 0, "Invalid swap quantity"); // 1. Load the bAssets from storage into memory BassetData[] memory allBassets = bAssetData; (uint8 inputIdx, ) = _getAsset(_input); (uint8 outputIdx, ) = _getAsset(_output); // 2. If a bAsset swap, calculate the validity, output and fee (swapOutput, ) = forgeValidator.computeSwap( allBassets, inputIdx, outputIdx, _inputQuantity, swapFee, _getConfig() ); } /*************************************** SWAP (INTERNAL) ****************************************/ /** @dev Swap single */ function _swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) internal returns (uint256 swapOutput) { require(_recipient != address(0), "Invalid recipient"); require(_input != _output, "Invalid pair"); require(_inputQuantity > 0, "Invalid swap quantity"); // 1. Load the bAssets from storage into memory BassetData[] memory allBassets = bAssetData; (uint8 inputIdx, BassetPersonal memory inputPersonal) = _getAsset(_input); (uint8 outputIdx, BassetPersonal memory outputPersonal) = _getAsset(_output); // 2. Load cache Cache memory cache = _getCacheDetails(); // 3. Deposit the input tokens uint256 quantityDeposited = Manager.depositTokens( inputPersonal, allBassets[inputIdx].ratio, _inputQuantity, cache.maxCache ); // 3.1. Update the input balance bAssetData[inputIdx].vaultBalance = allBassets[inputIdx].vaultBalance + SafeCast.toUint128(quantityDeposited); // 3. Validate the swap uint256 scaledFee; (swapOutput, scaledFee) = forgeValidator.computeSwap( allBassets, inputIdx, outputIdx, quantityDeposited, swapFee, _getConfig() ); require(swapOutput >= _minOutputQuantity, "Output qty < minimum qty"); require(swapOutput > 0, "Zero output quantity"); //4. Settle the swap //4.1. Decrease output bal Manager.withdrawTokens( swapOutput, outputPersonal, allBassets[outputIdx], _recipient, cache.maxCache ); bAssetData[outputIdx].vaultBalance = allBassets[outputIdx].vaultBalance - SafeCast.toUint128(swapOutput); // Save new surplus to storage surplus = cache.surplus + scaledFee; emit Swapped( msg.sender, inputPersonal.addr, outputPersonal.addr, swapOutput, scaledFee, _recipient ); } /*************************************** REDEMPTION (PUBLIC) ****************************************/ /** * @notice Redeems a specified quantity of mAsset in return for a bAsset specified by bAsset address. * The bAsset is sent to the specified recipient. * The bAsset quantity is relative to current vault balance levels and desired mAsset quantity. * The quantity of mAsset is burnt as payment. * A minimum quantity of bAsset is specified to protect against price slippage between the mAsset and bAsset. * @param _output Address of the bAsset to receive * @param _mAssetQuantity Quantity of mAsset to redeem * @param _minOutputQuantity Minimum bAsset quantity to receive for the burnt mAssets. This protects against slippage. * @param _recipient Address to transfer the withdrawn bAssets to. * @return outputQuantity Quanity of bAsset units received for the burnt mAssets */ function redeem( address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient ) external override nonReentrant whenNoRecol returns (uint256 outputQuantity) { outputQuantity = _redeem(_output, _mAssetQuantity, _minOutputQuantity, _recipient); } /** * @dev Credits a recipient with a proportionate amount of bAssets, relative to current vault * balance levels and desired mAsset quantity. Burns the mAsset as payment. * @param _mAssetQuantity Quantity of mAsset to redeem * @param _minOutputQuantities Min units of output to receive * @param _recipient Address to credit the withdrawn bAssets */ function redeemMasset( uint256 _mAssetQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) external override nonReentrant whenNoRecol returns (uint256[] memory outputQuantities) { outputQuantities = _redeemMasset(_mAssetQuantity, _minOutputQuantities, _recipient); } /** * @dev Credits a recipient with a certain quantity of selected bAssets, in exchange for burning the * relative Masset quantity from the sender. Sender also incurs a small fee on the outgoing asset. * @param _outputs Addresses of the bAssets to receive * @param _outputQuantities Units of the bAssets to redeem * @param _maxMassetQuantity Maximum mAsset quantity to burn for the received bAssets. This protects against slippage. * @param _recipient Address to receive the withdrawn bAssets * @return mAssetQuantity Quantity of mAsset units burned plus the swap fee to pay for the redeemed bAssets */ function redeemExactBassets( address[] calldata _outputs, uint256[] calldata _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) external override nonReentrant whenNoRecol returns (uint256 mAssetQuantity) { mAssetQuantity = _redeemExactBassets( _outputs, _outputQuantities, _maxMassetQuantity, _recipient ); } /** * @notice Gets the estimated output from a given redeem * @param _output Address of the bAsset to receive * @param _mAssetQuantity Quantity of mAsset to redeem * @return bAssetOutput Estimated quantity of bAsset units received for the burnt mAssets */ function getRedeemOutput(address _output, uint256 _mAssetQuantity) external view override returns (uint256 bAssetOutput) { require(_mAssetQuantity > 0, "Qty==0"); (uint8 idx, ) = _getAsset(_output); uint256 scaledFee = _mAssetQuantity.mulTruncate(swapFee); bAssetOutput = forgeValidator.computeRedeem( bAssetData, idx, _mAssetQuantity - scaledFee, _getConfig() ); } /** * @notice Gets the estimated output from a given redeem * @param _outputs Addresses of the bAsset to receive * @param _outputQuantities Quantities of bAsset to redeem * @return mAssetQuantity Estimated quantity of mAsset units needed to burn to receive output */ function getRedeemExactBassetsOutput( address[] calldata _outputs, uint256[] calldata _outputQuantities ) external view override returns (uint256 mAssetQuantity) { uint256 len = _outputQuantities.length; require(len > 0 && len == _outputs.length, "Invalid array input"); (uint8[] memory indexes, ) = _getBassets(_outputs); // calculate the value of mAssets need to cover the value of bAssets being redeemed uint256 mAssetRedeemed = forgeValidator.computeRedeemExact(bAssetData, indexes, _outputQuantities, _getConfig()); mAssetQuantity = mAssetRedeemed.divPrecisely(1e18 - swapFee) + 1; } /*************************************** REDEMPTION (INTERNAL) ****************************************/ /** * @dev Redeem mAsset for a single bAsset */ function _redeem( address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) internal returns (uint256 bAssetQuantity) { require(_recipient != address(0), "Invalid recipient"); require(_inputQuantity > 0, "Qty==0"); // Load the bAsset data from storage into memory BassetData[] memory allBassets = bAssetData; (uint8 bAssetIndex, BassetPersonal memory personal) = _getAsset(_output); // Calculate redemption quantities uint256 scaledFee = _inputQuantity.mulTruncate(swapFee); bAssetQuantity = forgeValidator.computeRedeem( allBassets, bAssetIndex, _inputQuantity - scaledFee, _getConfig() ); require(bAssetQuantity >= _minOutputQuantity, "bAsset qty < min qty"); require(bAssetQuantity > 0, "Output == 0"); // Apply fees, burn mAsset and return bAsset to recipient // 1.0. Burn the full amount of Masset _burn(msg.sender, _inputQuantity); surplus += scaledFee; Cache memory cache = _getCacheDetails(); // 2.0. Transfer the Bassets to the recipient Manager.withdrawTokens( bAssetQuantity, personal, allBassets[bAssetIndex], _recipient, cache.maxCache ); // 3.0. Set vault balance bAssetData[bAssetIndex].vaultBalance = allBassets[bAssetIndex].vaultBalance - SafeCast.toUint128(bAssetQuantity); emit Redeemed( msg.sender, _recipient, _inputQuantity, personal.addr, bAssetQuantity, scaledFee ); } /** * @dev Redeem mAsset for proportional amount of bAssets */ function _redeemMasset( uint256 _inputQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) internal returns (uint256[] memory outputQuantities) { require(_recipient != address(0), "Invalid recipient"); require(_inputQuantity > 0, "Qty==0"); // Calculate mAsset redemption quantities uint256 scaledFee = _inputQuantity.mulTruncate(redemptionFee); uint256 mAssetRedemptionAmount = _inputQuantity - scaledFee; // Burn mAsset quantity _burn(msg.sender, _inputQuantity); surplus += scaledFee; // Calc cache and total mAsset circulating Cache memory cache = _getCacheDetails(); // Total mAsset = (totalSupply + _inputQuantity - scaledFee) + surplus uint256 totalMasset = cache.vaultBalanceSum + mAssetRedemptionAmount; // Load the bAsset data from storage into memory BassetData[] memory allBassets = bAssetData; uint256 len = allBassets.length; address[] memory outputs = new address[](len); outputQuantities = new uint256[](len); for (uint256 i = 0; i < len; i++) { // Get amount out, proportionate to redemption quantity // Use `cache.sum` here as the total mAsset supply is actually totalSupply + surplus uint256 amountOut = (allBassets[i].vaultBalance * mAssetRedemptionAmount) / totalMasset; require(amountOut > 1, "Output == 0"); amountOut -= 1; require(amountOut >= _minOutputQuantities[i], "bAsset qty < min qty"); // Set output in array (outputQuantities[i], outputs[i]) = (amountOut, bAssetPersonal[i].addr); // Transfer the bAsset to the recipient Manager.withdrawTokens( amountOut, bAssetPersonal[i], allBassets[i], _recipient, cache.maxCache ); // reduce vaultBalance bAssetData[i].vaultBalance = allBassets[i].vaultBalance - SafeCast.toUint128(amountOut); } emit RedeemedMulti( msg.sender, _recipient, _inputQuantity, outputs, outputQuantities, scaledFee ); } /** @dev Redeem mAsset for one or more bAssets */ function _redeemExactBassets( address[] memory _outputs, uint256[] memory _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) internal returns (uint256 mAssetQuantity) { require(_recipient != address(0), "Invalid recipient"); uint256 len = _outputQuantities.length; require(len > 0 && len == _outputs.length, "Invalid array input"); require(_maxMassetQuantity > 0, "Qty==0"); (uint8[] memory indexes, BassetPersonal[] memory personal) = _getBassets(_outputs); // Load bAsset data from storage to memory BassetData[] memory allBassets = bAssetData; // Validate redemption uint256 mAssetRequired = forgeValidator.computeRedeemExact(allBassets, indexes, _outputQuantities, _getConfig()); mAssetQuantity = mAssetRequired.divPrecisely(1e18 - swapFee); uint256 fee = mAssetQuantity - mAssetRequired; require(mAssetQuantity > 0, "Must redeem some mAssets"); mAssetQuantity += 1; require(mAssetQuantity <= _maxMassetQuantity, "Redeem mAsset qty > max quantity"); // Apply fees, burn mAsset and return bAsset to recipient // 1.0. Burn the full amount of Masset _burn(msg.sender, mAssetQuantity); surplus += fee; Cache memory cache = _getCacheDetails(); // 2.0. Transfer the Bassets to the recipient and count fees for (uint256 i = 0; i < len; i++) { uint8 idx = indexes[i]; Manager.withdrawTokens( _outputQuantities[i], personal[i], allBassets[idx], _recipient, cache.maxCache ); bAssetData[idx].vaultBalance = allBassets[idx].vaultBalance - SafeCast.toUint128(_outputQuantities[i]); } emit RedeemedMulti( msg.sender, _recipient, mAssetQuantity, _outputs, _outputQuantities, fee ); } /*************************************** GETTERS ****************************************/ /** * @dev Get basket details for `Masset_MassetStructs.Basket` * @return b Basket struct */ function getBasket() external view override returns (bool, bool) { return (basket.undergoingRecol, basket.failed); } /** * @dev Get data for a all bAssets in basket * @return personal Struct[] with full bAsset data * @return data Number of bAssets in the Basket */ function getBassets() external view override returns (BassetPersonal[] memory personal, BassetData[] memory data) { return (bAssetPersonal, bAssetData); } /** * @dev Get data for a specific bAsset, if it exists * @param _bAsset Address of bAsset * @return personal Struct with full bAsset data * @return data Struct with full bAsset data */ function getBasset(address _bAsset) external view override returns (BassetPersonal memory personal, BassetData memory data) { uint8 idx = bAssetIndexes[_bAsset]; personal = bAssetPersonal[idx]; require(personal.addr == _bAsset, "Invalid asset"); data = bAssetData[idx]; } /** * @dev Gets all config needed for general InvariantValidator calls */ function getConfig() external view returns (InvariantConfig memory config) { return _getConfig(); } /*************************************** GETTERS - INTERNAL ****************************************/ /** * vaultBalanceSum = totalSupply + 'surplus' * maxCache = vaultBalanceSum * (cacheSize / 1e18) * surplus is simply surplus, to reduce SLOADs */ struct Cache { uint256 vaultBalanceSum; uint256 maxCache; uint256 surplus; } /** * @dev Gets the supply and cache details for the mAsset, taking into account the surplus * @return Cache containing (tracked) sum of vault balances, ideal cache size and surplus */ function _getCacheDetails() internal view returns (Cache memory) { // read surplus from storage into memory uint256 _surplus = surplus; uint256 sum = totalSupply() + _surplus; return Cache(sum, sum.mulTruncate(cacheSize), _surplus); } /** * @dev Gets a bAsset from storage * @param _asset Address of the asset * @return idx Index of the asset * @return personal Personal details for the asset */ function _getAsset(address _asset) internal view returns (uint8 idx, BassetPersonal memory personal) { idx = bAssetIndexes[_asset]; personal = bAssetPersonal[idx]; require(personal.addr == _asset, "Invalid asset"); } /** * @dev Gets a an array of bAssets from storage and protects against duplicates * @param _bAssets Addresses of the assets * @return indexes Indexes of the assets * @return personal Personal details for the assets */ function _getBassets(address[] memory _bAssets) internal view returns (uint8[] memory indexes, BassetPersonal[] memory personal) { uint256 len = _bAssets.length; indexes = new uint8[](len); personal = new BassetPersonal[](len); for (uint256 i = 0; i < len; i++) { (indexes[i], personal[i]) = _getAsset(_bAssets[i]); for (uint256 j = i + 1; j < len; j++) { require(_bAssets[i] != _bAssets[j], "Duplicate asset"); } } } /** * @dev Gets all config needed for general InvariantValidator calls */ function _getConfig() internal view returns (InvariantConfig memory) { return InvariantConfig(_getA(), weightLimits); } /** * @dev Gets current amplification var A */ function _getA() internal view returns (uint256) { AmpData memory ampData_ = ampData; uint64 endA = ampData_.targetA; uint64 endTime = ampData_.rampEndTime; // If still changing, work out based on current timestmap if (block.timestamp < endTime) { uint64 startA = ampData_.initialA; uint64 startTime = ampData_.rampStartTime; (uint256 elapsed, uint256 total) = (block.timestamp - startTime, endTime - startTime); if (endA > startA) { return startA + (((endA - startA) * elapsed) / total); } else { return startA - (((startA - endA) * elapsed) / total); } } // Else return final value else { return endA; } } /*************************************** YIELD ****************************************/ /** * @dev Converts recently accrued swap and redeem fees into mAsset * @return mintAmount mAsset units generated from swap and redeem fees * @return newSupply mAsset total supply after mint */ function collectInterest() external override onlySavingsManager returns (uint256 mintAmount, uint256 newSupply) { // Set the surplus variable to 1 to optimise for SSTORE costs. // If setting to 0 here, it would save 5k per savings deposit, but cost 20k for the // first surplus call (a SWAP or REDEEM). uint256 surplusFees = surplus; if (surplusFees > 1) { mintAmount = surplusFees - 1; surplus = 1; // mint new mAsset to savings manager _mint(msg.sender, mintAmount); emit MintedMulti( address(this), msg.sender, mintAmount, new address[](0), new uint256[](0) ); } newSupply = totalSupply(); } /** * @dev Collects the interest generated from the Basket, minting a relative * amount of mAsset and sends it over to the SavingsManager. * @return mintAmount mAsset units generated from interest collected from lending markets * @return newSupply mAsset total supply after mint */ function collectPlatformInterest() external override onlySavingsManager whenHealthy nonReentrant returns (uint256 mintAmount, uint256 newSupply) { uint256[] memory gains; (mintAmount, gains) = Manager.collectPlatformInterest( bAssetPersonal, bAssetData, forgeValidator, _getConfig() ); require(mintAmount > 0, "Must collect something"); _mint(msg.sender, mintAmount); emit MintedMulti(address(this), msg.sender, mintAmount, new address[](0), gains); newSupply = totalSupply(); } /*************************************** STATE ****************************************/ /** * @dev Sets the MAX cache size for each bAsset. The cache will actually revolve around * _cacheSize * totalSupply / 2 under normal circumstances. * @param _cacheSize Maximum percent of total mAsset supply to hold for each bAsset */ function setCacheSize(uint256 _cacheSize) external override onlyGovernor { require(_cacheSize <= 2e17, "Must be <= 20%"); cacheSize = _cacheSize; emit CacheSizeChanged(_cacheSize); } /** * @dev Upgrades the version of ForgeValidator protocol. Governor can do this * only while ForgeValidator is unlocked. * @param _newForgeValidator Address of the new ForgeValidator */ function upgradeForgeValidator(address _newForgeValidator) external override onlyGovernor { require(!forgeValidatorLocked, "ForgeVal locked"); require(_newForgeValidator != address(0), "Null address"); forgeValidator = IInvariantValidator(_newForgeValidator); emit ForgeValidatorChanged(_newForgeValidator); } /** * @dev Set the ecosystem fee for sewapping bAssets or redeeming specific bAssets * @param _swapFee Fee calculated in (%/100 * 1e18) */ function setFees(uint256 _swapFee, uint256 _redemptionFee) external override onlyGovernor { require(_swapFee <= MAX_FEE, "Swap rate oob"); require(_redemptionFee <= MAX_FEE, "Redemption rate oob"); swapFee = _swapFee; redemptionFee = _redemptionFee; emit FeesChanged(_swapFee, _redemptionFee); } /** * @dev Set the maximum weight for a given bAsset * @param _min Weight where 100% = 1e18 * @param _max Weight where 100% = 1e18 */ function setWeightLimits(uint128 _min, uint128 _max) external onlyGovernor { require(_min <= 1e18 / (bAssetData.length * 2), "Min weight oob"); require(_max >= 1e18 / (bAssetData.length - 1), "Max weight oob"); weightLimits = WeightLimits(_min, _max); emit WeightLimitsChanged(_min, _max); } /** * @dev Update transfer fee flag for a given bAsset, should it change its fee practice * @param _bAsset bAsset address * @param _flag Charge transfer fee when its set to 'true', otherwise 'false' */ function setTransferFeesFlag(address _bAsset, bool _flag) external override onlyGovernor { Manager.setTransferFeesFlag(bAssetPersonal, bAssetIndexes, _bAsset, _flag); } /** * @dev Transfers all collateral from one lending market to another - used initially * to handle the migration between Aave V1 and Aave V2. Note - only supports non * tx fee enabled assets. Supports going from no integration to integration, but * not the other way around. * @param _bAssets Array of basket assets to migrate * @param _newIntegration Address of the new platform integration */ function migrateBassets(address[] calldata _bAssets, address _newIntegration) external override onlyGovernor { Manager.migrateBassets(bAssetPersonal, bAssetIndexes, _bAssets, _newIntegration); } /** * @dev Executes the Auto Redistribution event by isolating the bAsset from the Basket * @param _bAsset Address of the ERC20 token to isolate * @param _belowPeg Bool to describe whether the bAsset deviated below peg (t) * or above (f) */ function handlePegLoss(address _bAsset, bool _belowPeg) external onlyGovernor { Manager.handlePegLoss(basket, bAssetPersonal, bAssetIndexes, _bAsset, _belowPeg); } /** * @dev Negates the isolation of a given bAsset * @param _bAsset Address of the bAsset */ function negateIsolation(address _bAsset) external onlyGovernor { Manager.negateIsolation(basket, bAssetPersonal, bAssetIndexes, _bAsset); } /** * @dev Starts changing of the amplification var A * @param _targetA Target A value * @param _rampEndTime Time at which A will arrive at _targetA */ function startRampA(uint256 _targetA, uint256 _rampEndTime) external onlyGovernor { Manager.startRampA(ampData, _targetA, _rampEndTime, _getA(), A_PRECISION); } /** * @dev Stops the changing of the amplification var A, setting * it to whatever the current value is. */ function stopRampA() external onlyGovernor { Manager.stopRampA(ampData, _getA()); } }
Get the projected output of a given mint _inputs Non-duplicate address array of addresses to bAssets to deposit for the minted mAsset tokens. _inputQuantities Quantity of each bAsset to deposit for the minted mAsset. return mintOutput Estimated mint output in mAsset terms/
function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view override returns (uint256 mintOutput) { uint256 len = _inputQuantities.length; require(len > 0 && len == _inputs.length, "Input array mismatch"); (uint8[] memory indexes, ) = _getBassets(_inputs); return forgeValidator.computeMintMulti(bAssetData, indexes, _inputQuantities, _getConfig()); }
2,378,750
/** *Submitted for verification at Etherscan.io on 2020-11-01 */ pragma solidity ^0.5.10; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Not authorized operation"); _; } /** * @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), "Address shouldn't be zero"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @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. * * > 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. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title Tozex ERC20 Mintable token * @dev Issue: contact support@tozex.io * @author Tozex.io */ contract MintableToken is ERC20, Ownable { using Address for address; using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public tokenOwner; address private crowdsale; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) internal allowed; event SetCrowdsale(address indexed _crowdsale); event Mint(address indexed to, uint256 amount); event MintFinished(); event UnlockToken(); event LockToken(); event Burn(); bool public mintingFinished = false; bool public locked = false; modifier canMint() { require(!mintingFinished); _; } modifier canTransfer() { require(!locked || msg.sender == owner); _; } modifier onlyCrowdsale() { require(msg.sender == crowdsale); _; } modifier onlyAuthorized() { require(msg.sender == owner || msg.sender == crowdsale); _; } constructor(string memory _name, string memory _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = 0; balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } /** * @dev Function to mint 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) public onlyAuthorized canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function burn(uint256 _value) public onlyAuthorized returns (bool) { totalSupply = totalSupply.sub(_value); balances[address(this)] = balances[address(this)].sub(_value); emit Burn(); emit Transfer(address(this), address(0), _value); return true; } /** * @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 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); emit Transfer(msg.sender, _to, _value); return true; } function transferFromContract(address _to, uint256 _value) public onlyOwner returns (bool) { require(_to != address(0)); require(_value <= balances[address(this)]); balances[address(this)] = balances[address(this)].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(address(this), _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]; } /** * @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 returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev 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); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (block.number > oldValue) { //injected CONTRACT AFFECTED BY MINERS allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function unlockToken() public onlyCrowdsale returns (bool) { locked = false; emit UnlockToken(); return true; } function lockToken() public onlyCrowdsale returns (bool) { locked = true; emit LockToken(); return true; } function setCrowdsale(address _crowdsale) public onlyOwner returns (bool) { require(_crowdsale.isContract()); crowdsale = _crowdsale; emit SetCrowdsale(_crowdsale); return true; } }
Function to stop minting new tokens. return True if the operation was successful./
function finishMinting() onlyOwner public canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; }
5,392,519
/* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.5; pragma experimental ABIEncoderV2; import "../src/Exchange.sol"; // solhint-disable no-empty-blocks contract TestExchangeInternals is Exchange { constructor () public Exchange("") {} /// @dev Adds properties of both FillResults instances. /// Modifies the first FillResults instance specified. /// Note that this function has been modified from the original // internal version to return the FillResults. /// @param totalFillResults Fill results instance that will be added onto. /// @param singleFillResults Fill results instance that will be added to totalFillResults. /// @return newTotalFillResults The result of adding singleFillResults to totalFilResults. function publicAddFillResults(FillResults memory totalFillResults, FillResults memory singleFillResults) public pure returns (FillResults memory) { addFillResults(totalFillResults, singleFillResults); return totalFillResults; } /// @dev Calculates amounts filled and fees paid by maker and taker. /// @param order to be filled. /// @param takerAssetFilledAmount Amount of takerAsset that will be filled. /// @return fillResults Amounts filled and fees paid by maker and taker. function publicCalculateFillResults( Order memory order, uint256 takerAssetFilledAmount ) public pure returns (FillResults memory fillResults) { return calculateFillResults(order, takerAssetFilledAmount); } /// @dev Calculates partial value given a numerator and denominator. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target. function publicSafeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) public pure returns (uint256 partialAmount) { return safeGetPartialAmountFloor(numerator, denominator, target); } /// @dev Calculates partial value given a numerator and denominator. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target. function publicSafeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) public pure returns (uint256 partialAmount) { return safeGetPartialAmountCeil(numerator, denominator, target); } /// @dev Calculates partial value given a numerator and denominator. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target. function publicGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) public pure returns (uint256 partialAmount) { return getPartialAmountFloor(numerator, denominator, target); } /// @dev Calculates partial value given a numerator and denominator. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target. function publicGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) public pure returns (uint256 partialAmount) { return getPartialAmountCeil(numerator, denominator, target); } /// @dev Checks if rounding error >= 0.1%. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function publicIsRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) public pure returns (bool isError) { return isRoundingErrorFloor(numerator, denominator, target); } /// @dev Checks if rounding error >= 0.1%. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function publicIsRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) public pure returns (bool isError) { return isRoundingErrorCeil(numerator, denominator, target); } /// @dev Updates state with results of a fill order. /// @param order that was filled. /// @param takerAddress Address of taker who filled the order. /// @param orderTakerAssetFilledAmount Amount of order already filled. /// @return fillResults Amounts filled and fees paid by maker and taker. function publicUpdateFilledState( Order memory order, address takerAddress, bytes32 orderHash, uint256 orderTakerAssetFilledAmount, FillResults memory fillResults ) public { updateFilledState( order, takerAddress, orderHash, orderTakerAssetFilledAmount, fillResults ); } }
Calculates partial value given a numerator and denominator. Reverts if rounding error is >= 0.1% numerator Numerator. denominator Denominator. target Value to calculate partial of. return Partial value of target.
function publicSafeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) public pure returns (uint256 partialAmount) { return safeGetPartialAmountCeil(numerator, denominator, target); }
5,455,225
./full_match/3/0x3c528EcF7A2e5D70A717A8d0e5daf0A18021cCB5/sources/browser/contracts/BRLx.sol
Usuário quer vender UtilityTokens em troca de BRLx um usuário chamou uma função do UTIL e queimou `tokens` tokens; recebemos um callback para mintar X BRLx para o usuário em troca do burn que ele efeutou;
function onTokensBurnedForTrade(address sender, uint tokens) public onlyUtilityToken whenNotPaused { require(tokens > 0, "Must send at least 1 token"); uint quote = quotes[msg.sender]; require(quote > 0, 'Quote not found'); uint tokensToMint = tokens * quote / 10000; emit Trade(sender, msg.sender, tokens, address(this), tokensToMint, quote); _mint(sender, tokensToMint); }
8,148,777
./full_match/4/0x259d29f29ce99e49959974F83F115C6f7352C697/sources/contracts/leo.sol
const Message payload e: data }; const encrypted = await EthCrypto.encryptWithPublicKey( publicKeyLeo, by encryping with bobs publicKey, only bob can decrypt the payload with his privateKey JSON.stringify(data) we have to stringify the payload before we can encrypt it ); const encryptedString = EthCrypto.cipher.stringify(encrypted); va.sendApplication(encryptedString); va.sendApplication(bytes(data));
function messageVulcan(string calldata data) public { IVulcanApplication(va_addr).sendApplication(bytes(data)); }
12,363,243
pragma solidity 0.4.25; // File: contracts/ERC777/ERC20Token.sol /* This Source Code Form is subject to the terms of the Mozilla external * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ interface ERC20Token { function name() external view returns (string); function symbol() external view returns (string); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // File: contracts/ERC820/ERC820Client.sol contract ERC820Registry { function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external; function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address); function setManager(address _addr, address _newManager) external; function getManager(address _addr) public view returns(address); } /// Base client to interact with the registry. contract ERC820Client { ERC820Registry erc820Registry = ERC820Registry(0x820c4597Fc3E4193282576750Ea4fcfe34DdF0a7); function setInterfaceImplementation(string _interfaceLabel, address _implementation) internal { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); erc820Registry.setInterfaceImplementer(this, interfaceHash, _implementation); } function interfaceAddr(address addr, string _interfaceLabel) internal view returns(address) { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); return erc820Registry.getInterfaceImplementer(addr, interfaceHash); } function delegateManagement(address _newManager) internal { erc820Registry.setManager(this, _newManager); } } // File: contracts/openzeppelin-solidity/math/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/openzeppelin-solidity/Address.sol /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/ERC777/ERC777Token.sol /* This Source Code Form is subject to the terms of the Mozilla external * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ interface ERC777Token { function name() external view returns (string); function symbol() external view returns (string); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function granularity() external view returns (uint256); function defaultOperators() external view returns (address[]); function isOperatorFor(address operator, address tokenHolder) external view returns (bool); function authorizeOperator(address operator) external; function revokeOperator(address operator) external; function send(address to, uint256 amount, bytes holderData) external; function operatorSend(address from, address to, uint256 amount, bytes holderData, bytes operatorData) external; function burn(uint256 amount, bytes holderData) external; function operatorBurn(address from, uint256 amount, bytes holderData, bytes operatorData) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes holderData, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes holderData, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // File: contracts/ERC777/ERC777TokensSender.sol /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ interface ERC777TokensSender { function tokensToSend( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) external; } // File: contracts/ERC777/ERC777TokensRecipient.sol /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ interface ERC777TokensRecipient { function tokensReceived( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) external; } // File: contracts/ERC777/ERC777BaseToken.sol /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ contract ERC777BaseToken is ERC777Token, ERC820Client { using SafeMath for uint256; using Address for address; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a SelfToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) external { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) external { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) external { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) external { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /// @return the name of the token function name() external view returns (string) { return mName; } /// @return the symbol of the token function symbol() external view returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() external view returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public view returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() external view returns (address[]) { return mDefaultOperators; } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. An operator cannot be reauthorized /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) external { require(_operator != msg.sender); require(!mAuthorized[_operator][msg.sender]); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } emit AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) external { require(_operator != msg.sender); require(mAuthorized[_operator][msg.sender]); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } emit RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return ( _operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder]) ); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); emit Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(!_to.isContract()); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } } // File: contracts/ERC777/ERC777ERC20BaseToken.sol /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken { bool internal mErc20compatible; mapping(address => mapping(address => uint256)) internal mAllowed; constructor( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible); _; } /// @notice For Backwards compatibility /// @return The decimls of the token. Forced to 18 in ERC777. function decimals() external erc20 view returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// 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 erc20 view returns (uint256 remaining) { return mAllowed[_owner][_spender]; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); if (mErc20compatible) { emit Transfer(_tokenHolder, 0x0, _amount); } } } // File: contracts/openzeppelin-solidity/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 OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/openzeppelin-solidity/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() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: contracts/utils/Freezable.sol /// @title An inheritable extension for a contract to freeze accessibility of any specific addresses /// @author Jeff Hu /// @notice Have a contract inherited from this to use the modifiers: whenAccountFrozen(), whenAccountNotFrozen() /// @dev Concern: Ownable may cause multiple owners; You need to pass in msg.sender when using modifiers contract Freezable is Ownable { event AccountFrozen(address indexed _account); event AccountUnfrozen(address indexed _account); // frozen status of all accounts mapping(address=>bool) public frozenAccounts; /** * @dev Modifier to make a function callable only when the address is frozen. */ modifier whenAccountFrozen(address _account) { require(frozenAccounts[_account] == true); _; } /** * @dev Modifier to make a function callable only when the address is not frozen. */ modifier whenAccountNotFrozen(address _account) { require(frozenAccounts[_account] == false); _; } /** * @dev Function to freeze an account from transactions */ function freeze(address _account) external onlyOwner whenAccountNotFrozen(_account) returns (bool) { frozenAccounts[_account] = true; emit AccountFrozen(_account); return true; } /** * @dev Function to unfreeze an account form frozen state */ function unfreeze(address _account) external onlyOwner whenAccountFrozen(_account) returns (bool) { frozenAccounts[_account] = false; emit AccountUnfrozen(_account); return true; } /** * @dev A user can choose to freeze her account (not unfreezable) */ function freezeMyAccount() external whenAccountNotFrozen(msg.sender) returns (bool) { // require(msg.sender != owner); // Only the owner cannot freeze herself frozenAccounts[msg.sender] = true; emit AccountFrozen(msg.sender); return true; } } // File: contracts/PausableFreezableERC777ERC20Token.sol /// @dev The owner can pause/unpause the token. /// When paused, all functions that may change the token balances are prohibited. /// Function approve is prohibited too. contract PausableFreezableERC777ERC20Token is ERC777ERC20BaseToken, Pausable, Freezable { // ERC777 methods /// @dev We can not call super.send() because send() is an external function. /// We can only override it. function send(address _to, uint256 _amount, bytes _userData) external whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_to) { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) external whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_from) whenAccountNotFrozen(_to) { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) external whenNotPaused whenAccountNotFrozen(msg.sender) { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) external whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_tokenHolder) { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } // ERC20 methods function transfer(address _to, uint256 _amount) public erc20 whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_to) returns (bool success) { return super.transfer(_to, _amount); } function transferFrom(address _from, address _to, uint256 _amount) public erc20 whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_from) whenAccountNotFrozen(_to) returns (bool success) { return super.transferFrom(_from, _to, _amount); } function approve(address _spender, uint256 _amount) public erc20 whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_spender) returns (bool success) { return super.approve(_spender, _amount); } /// @dev allow Owner to transfer funds from a Frozen account /// @notice the "_from" account must be frozen /// @notice only the owner can trigger this function /// @notice super.doSend to skip "_from" frozen checking function transferFromFrozenAccount( address _from, address _to, uint256 _amount ) external onlyOwner whenNotPaused whenAccountFrozen(_from) whenAccountNotFrozen(_to) whenAccountNotFrozen(msg.sender) { super.doSend(msg.sender, _from, _to, _amount, "", "", true); } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_operator) whenAccountNotFrozen(_from) whenAccountNotFrozen(_to) { super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_operator) whenAccountNotFrozen(_tokenHolder) { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); } } // File: contracts/ERC777ERC20TokenWithOfficialOperators.sol /// @title ERC777 ERC20 Token with Official Operators /// @author Roger-Wu /// @notice Official operators are officially recommended operator contracts. /// By adding new official operators, we can keep adding new features to /// an already deployed token contract, which can be viewed as a way to /// upgrade the token contract. /// Rules of official operators: /// 1. An official operator must be a contract. /// 2. An official operator can only be added or removed by the contract owner. /// 3. A token holder can either accept all official operators or not. /// By default, a token holder accepts all official operators, including /// the official operators added in the future. /// 4. If a token holder accepts all official operators, it works as if all /// the addresses of official operators has been authorized to be his operator. /// In this case, an official operator will always be the token holder's /// operator even if he tries to revoke it by sending `revokeOperator` transactions. /// 5. If a token holder chooses not to accept all official operators, it works as if /// there is no official operator at all for him. The token holder can still authorize /// any addresses, including which of official operators, to be his operators. contract ERC777ERC20TokenWithOfficialOperators is ERC777ERC20BaseToken, Ownable { using Address for address; mapping(address => bool) internal mIsOfficialOperator; mapping(address => bool) internal mIsUserNotAcceptingAllOfficialOperators; event OfficialOperatorAdded(address operator); event OfficialOperatorRemoved(address operator); event OfficialOperatorsAcceptedByUser(address indexed user); event OfficialOperatorsRejectedByUser(address indexed user); /// @notice Add an address into the list of official operators. /// @param _operator The address of a new official operator. /// An official operator must be a contract. function addOfficialOperator(address _operator) external onlyOwner { require(_operator.isContract(), "An official operator must be a contract."); require(!mIsOfficialOperator[_operator], "_operator is already an official operator."); mIsOfficialOperator[_operator] = true; emit OfficialOperatorAdded(_operator); } /// @notice Delete an address from the list of official operators. /// @param _operator The address of an official operator. function removeOfficialOperator(address _operator) external onlyOwner { require(mIsOfficialOperator[_operator], "_operator is not an official operator."); mIsOfficialOperator[_operator] = false; emit OfficialOperatorRemoved(_operator); } /// @notice Unauthorize all official operators to manage `msg.sender`'s tokens. function rejectAllOfficialOperators() external { require(!mIsUserNotAcceptingAllOfficialOperators[msg.sender], "Official operators are already rejected by msg.sender."); mIsUserNotAcceptingAllOfficialOperators[msg.sender] = true; emit OfficialOperatorsRejectedByUser(msg.sender); } /// @notice Authorize all official operators to manage `msg.sender`'s tokens. function acceptAllOfficialOperators() external { require(mIsUserNotAcceptingAllOfficialOperators[msg.sender], "Official operators are already accepted by msg.sender."); mIsUserNotAcceptingAllOfficialOperators[msg.sender] = false; emit OfficialOperatorsAcceptedByUser(msg.sender); } /// @return true if the address is an official operator, false if not. function isOfficialOperator(address _operator) external view returns(bool) { return mIsOfficialOperator[_operator]; } /// @return true if a user is accepting all official operators, false if not. function isUserAcceptingAllOfficialOperators(address _user) external view returns(bool) { return !mIsUserNotAcceptingAllOfficialOperators[_user]; } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return ( _operator == _tokenHolder || (!mIsUserNotAcceptingAllOfficialOperators[_tokenHolder] && mIsOfficialOperator[_operator]) || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder]) ); } } // File: contracts/ApprovalRecipient.sol interface ApprovalRecipient { function receiveApproval( address _from, uint256 _value, address _token, bytes _extraData ) external; } // File: contracts/ERC777ERC20TokenWithApproveAndCall.sol contract ERC777ERC20TokenWithApproveAndCall is PausableFreezableERC777ERC20Token { /// Set allowance for other address and notify /// Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it /// From https://www.ethereum.org/token /// @param _spender The address authorized to spend /// @param _value the max amount they can spend /// @param _extraData some extra information to send to the approved contract function approveAndCall(address _spender, uint256 _value, bytes _extraData) external whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_spender) returns (bool success) { ApprovalRecipient spender = ApprovalRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } } // File: contracts/ERC777ERC20TokenWithBatchTransfer.sol contract ERC777ERC20TokenWithBatchTransfer is PausableFreezableERC777ERC20Token { /// @notice ERC20 backwards compatible batch transfer. /// The transaction will revert if any of the recipients is frozen. /// We check whether a recipient is frozen in `doSend`. /// @param _recipients The addresses of the recipients /// @param _amounts The numbers of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function batchTransfer(address[] _recipients, uint256[] _amounts) external erc20 whenNotPaused whenAccountNotFrozen(msg.sender) returns (bool success) { require( _recipients.length == _amounts.length, "The lengths of _recipients and _amounts should be the same." ); for (uint256 i = 0; i < _recipients.length; i++) { doSend(msg.sender, msg.sender, _recipients[i], _amounts[i], "", "", false); } return true; } /// @notice Send tokens to multiple recipients. /// The transaction will revert if any of the recipients is frozen. /// We check whether a recipient is frozen in `doSend`. /// @param _recipients The addresses of the recipients /// @param _amounts The numbers of tokens to be transferred /// @param _userData Data generated by the user to be sent to the recipient function batchSend( address[] _recipients, uint256[] _amounts, bytes _userData ) external whenNotPaused whenAccountNotFrozen(msg.sender) { require( _recipients.length == _amounts.length, "The lengths of _recipients and _amounts should be the same." ); for (uint256 i = 0; i < _recipients.length; i++) { doSend(msg.sender, msg.sender, _recipients[i], _amounts[i], _userData, "", true); } } /// @notice Send tokens to multiple recipients on behalf of the address `from` /// The transaction will revert if any of the recipients is frozen. /// We check whether a recipient is frozen in `doSend`. /// @param _from The address holding the tokens being sent /// @param _recipients The addresses of the recipients /// @param _amounts The numbers of tokens to be transferred /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorBatchSend( address _from, address[] _recipients, uint256[] _amounts, bytes _userData, bytes _operatorData ) external whenNotPaused whenAccountNotFrozen(msg.sender) whenAccountNotFrozen(_from) { require( _recipients.length == _amounts.length, "The lengths of _recipients and _amounts should be the same." ); require(isOperatorFor(msg.sender, _from)); for (uint256 i = 0; i < _recipients.length; i++) { doSend(msg.sender, _from, _recipients[i], _amounts[i], _userData, _operatorData, true); } } } // File: contracts/CappedMintableERC777ERC20Token.sol /// @title Capped Mintable ERC777 ERC20 Token /// @author Roger-Wu /// @dev Mintable token with a minting cap. /// The owner can mint any amount of tokens until the cap is reached. contract CappedMintableERC777ERC20Token is ERC777ERC20BaseToken, Ownable { uint256 internal mTotalSupplyCap; constructor(uint256 _totalSupplyCap) public { mTotalSupplyCap = _totalSupplyCap; } /// @return the cap of total supply function totalSupplyCap() external view returns(uint _totalSupplyCap) { return mTotalSupplyCap; } /// @dev Generates `_amount` tokens to be assigned to `_tokenHolder` /// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. /// Reference: https://github.com/jacquesd/ERC777/blob/devel/contracts/examples/SelfToken.sol /// @param _tokenHolder The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @param _operatorData Data that will be passed to the recipient as a first transfer function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) external onlyOwner { requireMultiple(_amount); require(mTotalSupply.add(_amount) <= mTotalSupplyCap); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, address(0), _tokenHolder, _amount, "", _operatorData, true); emit Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { emit Transfer(0x0, _tokenHolder, _amount); } } } // File: contracts/ERC777ERC20TokenWithOperatorApprove.sol /// @title ERC777 ERC20 Token with Operator Approve /// @author Roger-Wu /// @notice Allow an operator to approve tokens for a token holder. contract ERC777ERC20TokenWithOperatorApprove is ERC777ERC20BaseToken { function operatorApprove( address _tokenHolder, address _spender, uint256 _amount ) external erc20 returns (bool success) { require( isOperatorFor(msg.sender, _tokenHolder), "msg.sender is not an operator for _tokenHolder" ); mAllowed[_tokenHolder][_spender] = _amount; emit Approval(_tokenHolder, _spender, _amount); return true; } } // File: contracts/openzeppelin-solidity/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/SelfToken.sol /// @title SelfToken /// @author Roger Wu (Roger-Wu), Tina Lee (tina1998612), Jeff Hu (yhuag) /// @dev The inheritance order is important. contract SelfToken is ERC777ERC20BaseToken, PausableFreezableERC777ERC20Token, ERC777ERC20TokenWithOfficialOperators, ERC777ERC20TokenWithApproveAndCall, ERC777ERC20TokenWithBatchTransfer, CappedMintableERC777ERC20Token, ERC777ERC20TokenWithOperatorApprove, Claimable { constructor() public ERC777ERC20BaseToken("SELF TOKEN", "SELF", 1, new address[](0)) CappedMintableERC777ERC20Token(1e9 * 1e18) {} }
Unauthorize all official operators to manage `msg.sender`'s tokens.
function rejectAllOfficialOperators() external { require(!mIsUserNotAcceptingAllOfficialOperators[msg.sender], "Official operators are already rejected by msg.sender."); mIsUserNotAcceptingAllOfficialOperators[msg.sender] = true; emit OfficialOperatorsRejectedByUser(msg.sender); }
7,310,119
// our mirrors: // ftec.io // ftec.ai // our official Telegram group: // t.me/FTECofficial pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ 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 MultiOwnable { mapping (address => bool) public isOwner; address[] public ownerHistory; event OwnerAddedEvent(address indexed _newOwner); event OwnerRemovedEvent(address indexed _oldOwner); function MultiOwnable() public { // Add default owner address owner = msg.sender; ownerHistory.push(owner); isOwner[owner] = true; } modifier onlyOwner() { require(isOwner[msg.sender]); _; } function ownerHistoryCount() public view returns (uint) { return ownerHistory.length; } /** Add extra owner. */ function addOwner(address owner) onlyOwner public { require(owner != address(0)); require(!isOwner[owner]); ownerHistory.push(owner); isOwner[owner] = true; OwnerAddedEvent(owner); } /** Remove extra owner. */ function removeOwner(address owner) onlyOwner public { require(isOwner[owner]); isOwner[owner] = false; OwnerRemovedEvent(owner); } } contract Pausable is MultiOwnable { bool public paused; modifier ifNotPaused { require(!paused); _; } modifier ifPaused { require(paused); _; } // Called by the owner on emergency, triggers paused state function pause() external onlyOwner ifNotPaused { paused = true; } // Called by the owner on end of emergency, returns to normal state function resume() external onlyOwner ifPaused { paused = false; } } contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is ERC20 { using SafeMath for uint; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { 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); Transfer(_from, _to, _value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract CommonToken is StandardToken, MultiOwnable { string public constant name = 'FTEC'; string public constant symbol = 'FTEC'; uint8 public constant decimals = 18; uint256 public saleLimit; // 85% of tokens for sale. uint256 public teamTokens; // 7% of tokens goes to the team and will be locked for 1 year. // 8% of the rest tokens will be used for bounty, advisors, and airdrops. // 7% of team tokens will be locked at this address for 1 year. address public teamWallet; // Team address. uint public unlockTeamTokensTime = now + 1 years; // The main account that holds all tokens at the beginning and during tokensale. address public seller; // Seller address (main holder of tokens) uint256 public tokensSold; // (e18) Number of tokens sold through all tiers or tokensales. uint256 public totalSales; // Total number of sales (including external sales) made through all tiers or tokensales. // Lock the transfer functions during tokensales to prevent price speculations. bool public locked = true; event SellEvent(address indexed _seller, address indexed _buyer, uint256 _value); event ChangeSellerEvent(address indexed _oldSeller, address indexed _newSeller); event Burn(address indexed _burner, uint256 _value); event Unlock(); function CommonToken( address _seller, address _teamWallet ) MultiOwnable() public { totalSupply = 998400000 ether; saleLimit = 848640000 ether; teamTokens = 69888000 ether; seller = _seller; teamWallet = _teamWallet; uint sellerTokens = totalSupply - teamTokens; balances[seller] = sellerTokens; Transfer(0x0, seller, sellerTokens); balances[teamWallet] = teamTokens; Transfer(0x0, teamWallet, teamTokens); } modifier ifUnlocked(address _from) { require(!locked); // If requested a transfer from the team wallet: if (_from == teamWallet) { require(now >= unlockTeamTokensTime); } _; } /** Can be called once by super owner. */ function unlock() onlyOwner public { require(locked); locked = false; Unlock(); } /** * An address can become a new seller only in case it has no tokens. * This is required to prevent stealing of tokens from newSeller via * 2 calls of this function. */ function changeSeller(address newSeller) onlyOwner public returns (bool) { require(newSeller != address(0)); require(seller != newSeller); // To prevent stealing of tokens from newSeller via 2 calls of changeSeller: require(balances[newSeller] == 0); address oldSeller = seller; uint256 unsoldTokens = balances[oldSeller]; balances[oldSeller] = 0; balances[newSeller] = unsoldTokens; Transfer(oldSeller, newSeller, unsoldTokens); seller = newSeller; ChangeSellerEvent(oldSeller, newSeller); return true; } /** * User-friendly alternative to sell() function. */ function sellNoDecimals(address _to, uint256 _value) public returns (bool) { return sell(_to, _value * 1e18); } function sell(address _to, uint256 _value) onlyOwner public returns (bool) { // Check that we are not out of limit and still can sell tokens: require(tokensSold.add(_value) <= saleLimit); require(_to != address(0)); require(_value > 0); require(_value <= balances[seller]); balances[seller] = balances[seller].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(seller, _to, _value); totalSales++; tokensSold = tokensSold.add(_value); SellEvent(seller, _to, _value); return true; } /** * Until all tokens are sold, tokens can be transfered to/from owner's accounts. */ function transfer(address _to, uint256 _value) ifUnlocked(msg.sender) public returns (bool) { return super.transfer(_to, _value); } /** * Until all tokens are sold, tokens can be transfered to/from owner's accounts. */ function transferFrom(address _from, address _to, uint256 _value) ifUnlocked(_from) public returns (bool) { return super.transferFrom(_from, _to, _value); } function burn(uint256 _value) public returns (bool) { require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); Burn(msg.sender, _value); return true; } } contract CommonTokensale is MultiOwnable, Pausable { using SafeMath for uint; address public beneficiary1; address public beneficiary2; address public beneficiary3; // Balances of beneficiaries: uint public balance1; uint public balance2; uint public balance3; // Token contract reference. CommonToken public token; uint public minPaymentWei = 0.1 ether; uint public minCapWei; uint public maxCapWei; uint public startTime; uint public endTime; // Stats for current tokensale: uint public totalTokensSold; // Total amount of tokens sold during this tokensale. uint public totalWeiReceived; // Total amount of wei received during this tokensale. // This mapping stores info on how many ETH (wei) have been sent to this tokensale from specific address. mapping (address => uint256) public buyerToSentWei; event ReceiveEthEvent(address indexed _buyer, uint256 _amountWei); function CommonTokensale( address _token, address _beneficiary1, address _beneficiary2, address _beneficiary3, uint _startTime, uint _endTime ) MultiOwnable() public { require(_token != address(0)); token = CommonToken(_token); beneficiary1 = _beneficiary1; beneficiary2 = _beneficiary2; beneficiary3 = _beneficiary3; startTime = _startTime; endTime = _endTime; } /** The fallback function corresponds to a donation in ETH. */ function() public payable { sellTokensForEth(msg.sender, msg.value); } function sellTokensForEth( address _buyer, uint256 _amountWei ) ifNotPaused internal { require(startTime <= now && now <= endTime); require(_amountWei >= minPaymentWei); require(totalWeiReceived.add(_amountWei) <= maxCapWei); uint tokensE18 = weiToTokens(_amountWei); // Transfer tokens to buyer. require(token.sell(_buyer, tokensE18)); // Update total stats: totalTokensSold = totalTokensSold.add(tokensE18); totalWeiReceived = totalWeiReceived.add(_amountWei); buyerToSentWei[_buyer] = buyerToSentWei[_buyer].add(_amountWei); ReceiveEthEvent(_buyer, _amountWei); // Split received amount between balances of three beneficiaries. uint part = _amountWei / 3; balance1 = balance1.add(_amountWei - part * 2); balance2 = balance2.add(part); balance3 = balance3.add(part); } /** Calc how much tokens you can buy at current time. */ function weiToTokens(uint _amountWei) public view returns (uint) { return _amountWei.mul(tokensPerWei(_amountWei)); } function tokensPerWei(uint _amountWei) public view returns (uint256) { uint expectedTotal = totalWeiReceived.add(_amountWei); // Presale pricing rules: if (expectedTotal < 1000 ether) return 39960; if (expectedTotal < 2000 ether) return 37480; if (expectedTotal < 4000 ether) return 35270; // Public sale pricing rules: if (expectedTotal < 6000 ether) return 33300; if (expectedTotal < 8000 ether) return 32580; if (expectedTotal < 11000 ether) return 31880; if (expectedTotal < 15500 ether) return 31220; if (expectedTotal < 20500 ether) return 30590; if (expectedTotal < 26500 ether) return 29970; return 29970; // Default token price with no bonuses. } function canWithdraw() public view returns (bool); function withdraw1(address _to) public { require(canWithdraw()); require(msg.sender == beneficiary1); require(balance1 > 0); uint bal = balance1; balance1 = 0; _to.transfer(bal); } function withdraw2(address _to) public { require(canWithdraw()); require(msg.sender == beneficiary2); require(balance2 > 0); uint bal = balance2; balance2 = 0; _to.transfer(bal); } function withdraw3(address _to) public { require(canWithdraw()); require(msg.sender == beneficiary3); require(balance3 > 0); uint bal = balance3; balance3 = 0; _to.transfer(bal); } } contract Presale is CommonTokensale { // In case min (soft) cap is not reached, token buyers will be able to // refund their contributions during 3 months after presale is finished. uint public refundDeadlineTime; // Total amount of wei refunded if min (soft) cap is not reached. uint public totalWeiRefunded; event RefundEthEvent(address indexed _buyer, uint256 _amountWei); function Presale( address _token, address _beneficiary1, address _beneficiary2, address _beneficiary3, uint _startTime, uint _endTime ) CommonTokensale( _token, _beneficiary1, _beneficiary2, _beneficiary3, _startTime, _endTime ) public { minCapWei = 2000 ether; maxCapWei = 4000 ether; refundDeadlineTime = _endTime + 3 * 30 days; } /** * During presale it will be possible to withdraw only in two cases: * min cap reached OR refund period expired. */ function canWithdraw() public view returns (bool) { return totalWeiReceived >= minCapWei || now > refundDeadlineTime; } /** * It will be possible to refund only if min (soft) cap is not reached and * refund requested during 3 months after presale finished. */ function canRefund() public view returns (bool) { return totalWeiReceived < minCapWei && endTime < now && now <= refundDeadlineTime; } function refund() public { require(canRefund()); address buyer = msg.sender; uint amount = buyerToSentWei[buyer]; require(amount > 0); // Redistribute left balance between three beneficiaries. uint newBal = this.balance.sub(amount); uint part = newBal / 3; balance1 = newBal - part * 2; balance2 = part; balance3 = part; RefundEthEvent(buyer, amount); buyerToSentWei[buyer] = 0; totalWeiRefunded = totalWeiRefunded.add(amount); buyer.transfer(amount); } } contract ProdPresale is Presale { function ProdPresale() Presale( 0x6BeC54E4fEa5d541fB14de96993b8E11d81159b2, 0x5cAEDf960efC2F586B0260B8B4B3C5738067c3af, 0xec6014B7FF9E510D43889f49AE019BAD6EA35039, 0x234066EEa7B0E9539Ef1f6281f3Ca8aC5e922363, 1524578400, 1526997600 ) public {} }
Transfer tokens to buyer. Update total stats: Split received amount between balances of three beneficiaries.
function sellTokensForEth( address _buyer, uint256 _amountWei ) ifNotPaused internal { require(startTime <= now && now <= endTime); require(_amountWei >= minPaymentWei); require(totalWeiReceived.add(_amountWei) <= maxCapWei); uint tokensE18 = weiToTokens(_amountWei); require(token.sell(_buyer, tokensE18)); totalTokensSold = totalTokensSold.add(tokensE18); totalWeiReceived = totalWeiReceived.add(_amountWei); buyerToSentWei[_buyer] = buyerToSentWei[_buyer].add(_amountWei); ReceiveEthEvent(_buyer, _amountWei); uint part = _amountWei / 3; balance1 = balance1.add(_amountWei - part * 2); balance2 = balance2.add(part); balance3 = balance3.add(part); }
7,298,367
./partial_match/1/0x6DC6fd523A9F54BC6640e810f5b53d90AB270f11/sources/pepe.sol
exclude from paying fees or having max transaction amount
constructor() ERC20(unicode"pepe ccoin", unicode"pepe") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 20; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 50; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; maxWallet = 20_000_000 * 1e18; swapTokensAtAmount = (totalSupply * 5) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
15,525,190
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol
Reads the int216 at `cdPtr` in calldata.
function readInt216( CalldataPointer cdPtr ) internal pure returns (int216 value) { assembly { value := calldataload(cdPtr) } }
4,300,328
./partial_match/1313161554/0xa200B567579a577F582d292f7A1b5C4ecce195F8/sources/Comptroller.sol
Claim all PLY or AURORA accrued by one holder Only whitelisted address can claim the rewards for other users. This is to prevent users to lock others' reward into token lock. rewardType 0: Ply, 1: Aurora holder The address to claim PLY / AURORA for auTokens The list of markets to claim PLY / AURORA in borrowers Whether or not to claim PLY / AURORA earned by borrowing suppliers Whether or not to claim PLY / AURORA earned by supplying/
function _claimRewardForOne(uint8 rewardType, address holder, AuToken[] memory auTokens, bool borrowers, bool suppliers) internal { checkRewardType(rewardType); require(borrowers||suppliers,"either borrow or supply must be true"); require(isAllowedToClaimReward(holder, msg.sender), "not approved"); for (uint i = 0; i < auTokens.length; i++) { AuToken auToken = auTokens[i]; require(markets[address(auToken)].isListed, "market must be listed"); if (borrowers) { Exp borrowIndex = Exp.wrap(auToken.borrowIndex()); (uint totalBorrows, uint borrowBalanceStored) = auToken.getBorrowDataOfAccount(holder); updateRewardBorrowIndex(rewardType, address(auToken), borrowIndex, totalBorrows); distributeBorrowerReward(rewardType, address(auToken), holder, borrowIndex, borrowBalanceStored); } if (suppliers) { (uint totalSupply, uint auTokenBalance) = auToken.getSupplyDataOfOneAccount(holder); updateRewardSupplyIndex(rewardType, address(auToken), totalSupply); distributeSupplierReward(rewardType, address(auToken), holder, auTokenBalance); } } uint256 holderReward = rewardAccrued[rewardType][holder]; rewardAccrued[rewardType][holder] = 0; doTransferOutRewards(rewardType, holder, holderReward); }
16,936,513
./full_match/80001/0xa804650B1C4Ff76A4EF10eaEbBFAa9bE5e81E32e/sources/contracts/ERC721NESStakingController.sol
Stakes a token and records the start block number or time stamp./
function stake(uint256 tokenId) public { require( ERC721NES(tokenContract).ownerOf(tokenId) == msg.sender, "You are not the owner of this token" ); tokenToWhenStaked[tokenId] = block.number; ERC721NES(tokenContract).stakeFromController(tokenId, msg.sender); }
9,446,347
./full_match/80001/0xeA2F671AFB61B6ca8Eb2290f91aBfF425bA083f2/sources/project_/contracts/Seller.sol
EUR-USD STABLE_COIN-USD STABLE_COIN-EUR => How many Stable Coins for one Euro
function getPriceOneEuroStableCoin() internal view returns(int256) { int256 decimals = int256(10 ** uint256(18)); ( , int256 basePrice, , , ) = S_PRICE_FEED_EUR_USD.latestRoundData(); uint8 baseDecimals = S_PRICE_FEED_EUR_USD.decimals(); basePrice = scalePrice(basePrice, baseDecimals, uint8(18)); ( , int256 quotePrice, , , ) = S_PRICE_FEED_STABLECOIN_USD.latestRoundData(); uint8 quoteDecimals = S_PRICE_FEED_STABLECOIN_USD.decimals(); quotePrice = scalePrice(quotePrice, quoteDecimals, uint8(18)); return basePrice * decimals / quotePrice; }
5,614,177
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract AMM { using SafeMath for uint256; uint totalShares; // Stores the total amount of share issued for the pool uint totalToken1; // Stores the amount of Token1 locked in the pool uint totalToken2; // Stores the amount of Token2 locked in the pool uint K; // Algoritmic constant used to determine price (K = totalToken1 * totalToken2) uint constant PRECISION = 1_000_000; // Precisioin of 6 decimal places mapping(address => uint) shares; // Stores the share holding of each provider mapping(address => uint) token1Balance; // Stores the available balance of user outside of the AMM mapping(address => uint) token2Balance; // Ensure that the _qty is non-zero and the user has enough balance modifier validAmountCheck(mapping(address => uint)storage _balance, uint _qty ) { require(_qty > 0, "Amount cannot be zero!"); require(_qty <= _balance[msg.sender], "Insufficient amount"); _; } // Restricts withdraw, swap feature till liquidity is added to the pool modifier activePool() { require(totalShares > 0 , "Zero Liquidity"); _; } // Returns the balance of the user function getMyHoldings() external view returns(uint amountToken1, uint amountToken2, uint myShare){ amountToken1 = token1Balance[msg.sender]; amountToken2 = token2Balance[msg.sender]; myShare = shares[msg.sender]; } // Returns the total amount of tokens in the pool and the total share issued corresponding to it function getPoolDetails() external view returns(uint, uint, uint){ return (totalToken1, totalToken2, totalShares); } // Sends free tokens to the invoker function faucet(uint256 _amountToken1, uint _amountToken2) external { token1Balance[msg.sender] = token1Balance[msg.sender].add(_amountToken1); token2Balance[msg.sender] = token2Balance[msg.sender].add(_amountToken2); } // Adding new liquidity in the pool // Returns the amount of share issued for locking given assets function provide(uint256 _amountToken1, uint256 _amountToken2) external validAmountCheck(token1Balance, _amountToken1) validAmountCheck(token2Balance, _amountToken2) returns(uint256 share) { if(totalShares == 0) { // Genesis liquidity is issued 100 Shares share = 100*PRECISION; } else{ uint256 share1 = totalShares.mul(_amountToken1).div(totalToken1); uint256 share2 = totalShares.mul(_amountToken2).div(totalToken2); require(share1 == share2, "Equivalent value of tokens not provided..."); share = share1; } require(share > 0, "Asset value less than threshold for contribution!"); token1Balance[msg.sender] -= _amountToken1; token2Balance[msg.sender] -= _amountToken2; totalToken1 += _amountToken1; totalToken2 += _amountToken2; K = totalToken1.mul(totalToken2); totalShares += share; shares[msg.sender] += share; } // Returns amount of Token1 required when providing liquidity with _amountToken2 quantity of Token2 function getEquivalentToken1Estimate(uint256 _amountToken2) public view activePool returns(uint256 reqToken1) { reqToken1 = totalToken1.mul(_amountToken2).div(totalToken2); } // Returns amount of Token2 required when providing liquidity with _amountToken1 quantity of Token1 function getEquivalentToken2Estimate(uint256 _amountToken1) public view activePool returns(uint256 reqToken2) { reqToken2 = totalToken2.mul(_amountToken1).div(totalToken1); } // Returns the estimate of Token1 & Token2 that will be released on burning given _share function getWithdrawEstimate(uint256 _share) public view activePool returns(uint256 amountToken1, uint256 amountToken2){ require(_share <= totalShares, "Share should be less than totalShare"); amountToken1 = _share.mul(totalToken1).div(totalShares); amountToken2 = _share.mul(totalToken2).div(totalShares); } // Removes liquidity from the pool and releases corresponding Token1 & Token2 to the withdrawer function withdraw(uint256 _share) external activePool validAmountCheck(shares, _share) returns(uint256 amountToken1, uint256 amountToken2){ (amountToken1, amountToken2) = getWithdrawEstimate(_share); shares[msg.sender] -= _share; totalShares -= _share; totalToken1 -= amountToken1; totalToken2 -= amountToken2; K = totalToken1.mul(totalToken2); token1Balance[msg.sender] += amountToken1; token2Balance[msg.sender] += amountToken2; } // Returns the amount of Token2 that the user will get when swapping a given amount of Token1 for Token2 function getSwapToken1Estimate(uint256 _amountToken1) public view activePool returns(uint256 amountToken2){ uint256 token1After = totalToken1.add(_amountToken1); uint256 token2After = K.div(token1After); amountToken2 = totalToken2.sub(token2After); // To ensure that Token2's pool is not completely depleted leading to inf:0 ratio if(amountToken2 == totalToken2) amountToken2--; } // Returns the amount of Token1 that the user should swap to get _amountToken2 in return function getSwapTokenEstimateGivenToken2(uint256 _amountToken2) public view activePool returns(uint256 amountToken1){ require(_amountToken2 < totalToken2,"Insufficient pool balance"); uint256 token2After = totalToken2.sub(_amountToken2); uint256 token1After = K.div(token2After); amountToken1 = token1After.sub(totalToken1); } // Swaps given amount of Token1 to Token2 using algorithmic price determination function swapToken1(uint256 _amountToken1) external activePool validAmountCheck(token1Balance, _amountToken1) returns(uint256 amountToken2){ amountToken2 = getSwapToken1Estimate(_amountToken1); token1Balance[msg.sender] -= _amountToken1; totalToken1 += _amountToken1; totalToken2 -= amountToken2; token2Balance[msg.sender] += amountToken2; } // Returns the amount of Token2 that the user will get when swapping a given amount of Token1 for Token2 function getSwapToken2Estimate(uint256 _amountToken2) public view activePool returns(uint256 amountToken1) { uint256 token2After = totalToken2.add(_amountToken2); uint256 token1After = K.div(token2After); amountToken1 = totalToken1.sub(token1After); // To ensure that Token1's pool is not completely depleted leading to inf:0 ratio if(amountToken1 == totalToken1) amountToken1--; } // Returns the amount of Token2 that the user should swap to get _amountToken1 in return function getSwapToken2EstimateGivenToken1(uint256 _amountToken1) public view activePool returns(uint256 amountToken2) { require(_amountToken1 < totalToken1, "Insufficient pool balance"); uint256 token1After = totalToken1.sub(_amountToken1); uint256 token2After = K.div(token1After); amountToken2 = token2After.sub(totalToken2); } // Swaps given amount of Token2 to Token1 using algorithmic price determination function swapToken2(uint256 _amountToken2) external activePool validAmountCheck(token2Balance, _amountToken2) returns(uint256 amountToken1) { amountToken1 = getSwapToken2Estimate(_amountToken2); token2Balance[msg.sender] -= _amountToken2; totalToken2 += _amountToken2; totalToken1 -= amountToken1; token1Balance[msg.sender] += amountToken1; } }
Swaps given amount of Token2 to Token1 using algorithmic price determination
function swapToken2(uint256 _amountToken2) external activePool validAmountCheck(token2Balance, _amountToken2) returns(uint256 amountToken1) { amountToken1 = getSwapToken2Estimate(_amountToken2); token2Balance[msg.sender] -= _amountToken2; totalToken2 += _amountToken2; totalToken1 -= amountToken1; token1Balance[msg.sender] += amountToken1; }
5,372,384
./partial_match/56/0xfc96E7d7EECf17523f09023e650318C0bbf2d1Ba/sources/ABCToken.sol
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/
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), "ABC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "ABC::delegateBySig: invalid nonce"); require(now <= expiry, "ABC::delegateBySig: signature expired"); return _delegate(signatory, delegatee); }
11,256,858
./full_match/42161/0xc6CcA907A475a70B2052582A0d52674d997a2c67/sources/contracts/EscrowAndStaking/StakingThales.sol
Claim the weekly staking rewards on behalf of the account account to claim on behalf of
function claimRewardOnBehalf(address account) public nonReentrant notPaused { require(account != address(0) && account != msg.sender, "Invalid address"); require(canClaimOnBehalf[account][msg.sender], "Cannot claim on behalf"); _claimReward(account); }
16,302,273
./full_match/42161/0x8B87E0b9a093B4f209F26Bd5ca664B7C6986220F/sources/contracts/StandWithCrypto.sol
Function to update the status of free and paid selfdrop
function updateSelfdrop(bool _enableFREE, bool _enablePAID) external onlyOwner { enableFREE = _enableFREE; enablePAID = _enablePAID; }
16,309,813
./partial_match/1/0xEC233143B85892dd6A6E2dc48D7F73aF728d7164/sources/alch.sol
Updates `owner` s allowance for `spender` based on spent `amount`. Does not update the allowance amount in case of infinite allowance. Revert if not enough allowance is available. Might emit an {Approval} event./
function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "ERC20: insufficient allowance" ); unchecked { _approve(owner, spender, currentAllowance - amount); } } }
2,622,284
./full_match/5/0xB679452E6E41d7CeAa70D59A0f6F756F0362571A/sources/contracts/OratisNFT.sol
Update the public mint price in usdc. 6 decimal places _usdcPublicPrice the price per NFT in USDC. Remember 6 decimal places./
function setUsdcPublicPrice(uint256 _usdcPublicPrice) external onlyOwner { usdcPublicPrice = _usdcPublicPrice; }
11,589,644
./full_match/1/0x08e2dd6A661d91C3Aa8b8E4ac1342a3C60be6857/sources/YGGD.sol
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(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); }
2,906,931
// SPDX-License-Identifier: MIT // _ ______________ ____________ // / | / / ____/_ __/__ / ____/ ____/_________ ____ ___ // / |/ / /_ / / / _ \/ / __/ / __ / ___/ __ \/ __ `__ \ // / /| / __/ / / / __/ /_/ / /_/ // /__/ /_/ / / / / / / // /_/ |_/_/ /_/ \___/\____/\____(_)___/\____/_/ /_/ /_/ pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } /** * @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.3._ */ 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.3._ */ 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev 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(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)); } } /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } pragma solidity >=0.6.0 <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 Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @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 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); } /** * @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 ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // ################################################# /** * @dev Contract module that can be used to recover ERC20 compatible tokens stuck in the contract. */ contract ERC20Recoverable is Ownable { /** * @dev Used to transfer tokens stuck on this contract to another address. */ function recoverERC20(address token, address recipient, uint256 amount) external onlyOwner returns (bool) { return IERC20(token).transfer(recipient, amount); } /** * @dev Used to approve recovery of stuck tokens. May also be used to approve token transfers in advance. */ function recoverERC20Approve(address token, address spender, uint256 amount) external onlyOwner returns (bool) { return IERC20(token).approve(spender, amount); } } /** * @dev Contract module that can be used to recover ERC721 compatible tokens stuck in the contract. */ contract ERC721Recoverable is Ownable { /** * @dev Used to recover a stuck token. */ function recoverERC721(address token, address recipient, uint256 tokenId) external onlyOwner { return IERC721(token).transferFrom(address(this), recipient, tokenId); } /** * @dev Used to recover a stuck token using the safe transfer function of ERC721. */ function recoverERC721Safe(address token, address recipient, uint256 tokenId) external onlyOwner { return IERC721(token).safeTransferFrom(address(this), recipient, tokenId); } /** * @dev Used to approve the recovery of a stuck token. */ function recoverERC721Approve(address token, address recipient, uint256 tokenId) external onlyOwner { return IERC721(token).approve(recipient, tokenId); } /** * @dev Used to approve the recovery of stuck token, also in future. */ function recoverERC721ApproveAll(address token, address recipient, bool approved) external onlyOwner { return IERC721(token).setApprovalForAll(recipient, approved); } } /** * @dev Most credited to OpenZeppelin ERC721.sol, but with some adjustments. */ contract T2 is Context, Ownable, ERC165, IERC721, IERC721Metadata, IERC721Enumerable, ERC20Recoverable, ERC721Recoverable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Specified if tokens are transferable. Can be flipped by the owner. bool private _transferable; // Price per token. Is chosen and can be changed by contract owner. uint256 private _tokenPrice; // Counter for token id uint256 private _nextId = 1; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol, string memory baseURI, bool transferable, uint256 tokenPrice) public { _name = name; _symbol = symbol; _baseURI = baseURI; _transferable = transferable; _tokenPrice = tokenPrice; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } // public functions: /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) external view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() external view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() external view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() external view returns (string memory) { return _baseURI; } /** * @dev Returns if tokens are globally transferable currently. That may be decided by the contract owner. */ function transferable() external view returns (bool) { return _transferable; } /** * @dev Price per token for public purchase. */ function tokenPrice() external view returns (uint256) { return _tokenPrice; } /** * @dev Next token id. */ function nextTokenId() public view returns (uint256) { return _nextId; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() external view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) external view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) external virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) external virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) external 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) external 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); } function buyToken() external payable returns (bool) { uint256 paidAmount = msg.value; require(paidAmount == _tokenPrice, "Invalid amount for token purchase"); _mint(msg.sender, nextTokenId()); _incrementTokenId(); payable(owner()).transfer(paidAmount); return true; } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public returns (bool) { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); return true; } function burnAnyFrom(address burner) public returns (bool) { require(_holderTokens[burner].length() > 0, "Address does not have any tokens to burn"); return burn(_holderTokens[burner].at(0)); } function burnAny() external returns (bool) { return burnAnyFrom(msg.sender); } // owner functions: /** * @dev Function to set the base URI for all token IDs. It is automatically added as a prefix to the token id in {tokenURI} to retrieve the token URI. */ function setBaseURI(string calldata baseURI_) external onlyOwner { _baseURI = baseURI_; } /** * @dev Function for the contract owner to allow or disallow token transfers. */ function setTransferable(bool allowed) external onlyOwner { _transferable = allowed; } /** * @dev Sets a new token price. */ function setTokenPrice(uint256 newPrice) external onlyOwner { _tokenPrice = newPrice; } // internal functions: /** * @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) private { _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) private view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) private view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) private { _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) private { _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) private { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - contract owner must have transfer globally allowed. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) private { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); require(_transferable == true, "ERC721 transfer not permitted by contract owner"); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } function _incrementTokenId() private { _nextId = _nextId.add(1); } } /** * @dev Most credited to OpenZeppelin ERC721.sol, but with some adjustments. */ contract T1 is Context, Ownable, ERC165, IERC721, IERC721Metadata, IERC721Enumerable, ERC20Recoverable, ERC721Recoverable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // ERC721 token contract address serving as "ticket" to flip the bool in additional data address private _ticketContract; // Base URI string private _baseURI; // Price per token. Is chosen and can be changed by contract owner. uint256 private _tokenPrice; struct AdditionalData { bool isA; // A (true) or B (false) bool someBool; // may be flipped by token owner if he owns T2; default value in _mint uint8 power; } // Mapping from token ID to its additional data mapping (uint256 => AdditionalData) private _additionalData; // Counter for token id, and types uint256 private _nextId = 1; uint32 private _countA = 0; // count of B is implicit and not needed mapping (address => bool) public freeBoolSetters; // addresses which do not need to pay to set the bool variable // limits uint256 public constant MAX_SUPPLY = 7000; uint32 public constant MAX_A = 1000; uint32 public constant MAX_B = 6000; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol, string memory baseURI, uint256 tokenPrice, address ticketContract) public { _name = name; _symbol = symbol; _baseURI = baseURI; _tokenPrice = tokenPrice; _ticketContract = ticketContract; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } // public functions: /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() external view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() external view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() external view returns (string memory) { return _baseURI; } /** * @dev Retrieves address of the ticket token contract. */ function ticketContract() external view returns (address) { return _ticketContract; } /** * @dev Price per token for public purchase. */ function tokenPrice() external view returns (uint256) { return _tokenPrice; } /** * @dev Next token id. */ function nextTokenId() public view returns (uint256) { return _nextId; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { require(index < balanceOf(owner), "Invalid token index for holder"); return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() external view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev Supply of A tokens. */ function supplyOfA() external view returns (uint256) { return _countA; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) external view override returns (uint256) { require(index < _tokenOwners.length(), "Invalid token index"); (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) external virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) external virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) external 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) external 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 Buys a token. Needs to be supplied the correct amount of ether. */ function buyToken() external payable returns (bool) { uint256 paidAmount = msg.value; require(paidAmount == _tokenPrice, "Invalid amount for token purchase"); address to = msg.sender; uint256 nextToken = nextTokenId(); uint256 remainingTokens = 1 + MAX_SUPPLY - nextToken; require(remainingTokens > 0, "Maximum supply already reached"); _holderTokens[to].add(nextToken); _tokenOwners.set(nextToken, to); uint256 remainingA = MAX_A - _countA; bool a = (uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now, nextToken))) % remainingTokens) < remainingA; uint8 pow = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now + 1, nextToken))) % (a ? 21 : 79) + (a ? 80 : 1)); _additionalData[nextToken] = AdditionalData(a, false, pow); if (a) { _countA = _countA + 1; } emit Transfer(address(0), to, nextToken); _nextId = nextToken.add(1); payable(owner()).transfer(paidAmount); return true; } function buy6Tokens() external payable returns (bool) { uint256 paidAmount = msg.value; require(paidAmount == (_tokenPrice * 5 + _tokenPrice / 2), "Invalid amount for token purchase"); // price for 6 tokens is 5.5 times the price for one token address to = msg.sender; uint256 nextToken = nextTokenId(); uint256 remainingTokens = 1 + MAX_SUPPLY - nextToken; require(remainingTokens > 5, "Maximum supply already reached"); uint256 endLoop = nextToken.add(6); while (nextToken < endLoop) { _holderTokens[to].add(nextToken); _tokenOwners.set(nextToken, to); uint256 remainingA = MAX_A - _countA; bool a = (uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now, nextToken))) % remainingTokens) < remainingA; uint8 pow = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now + 1, nextToken))) % (a ? 21 : 79) + (a ? 80 : 1)); _additionalData[nextToken] = AdditionalData(a, false, pow); if (a) { _countA = _countA + 1; } emit Transfer(address(0), to, nextToken); nextToken = nextToken.add(1); remainingTokens = remainingTokens.sub(1); } _nextId = _nextId.add(6); payable(owner()).transfer(paidAmount); return true; } function buyTokenTo(address to) external payable returns (bool) { uint256 paidAmount = msg.value; require(paidAmount == _tokenPrice, "Invalid amount for token purchase"); uint256 nextToken = nextTokenId(); uint256 remainingTokens = 1 + MAX_SUPPLY - nextToken; require(remainingTokens > 0, "Maximum supply already reached"); _holderTokens[to].add(nextToken); _tokenOwners.set(nextToken, to); uint256 remainingA = MAX_A - _countA; bool a = (uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now, nextToken))) % remainingTokens) < remainingA; uint8 pow = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now + 1, nextToken))) % (a ? 21 : 79) + (a ? 80 : 1)); _additionalData[nextToken] = AdditionalData(a, false, pow); if (a) { _countA = _countA + 1; } emit Transfer(address(0), to, nextToken); _nextId = nextToken.add(1); payable(owner()).transfer(paidAmount); return true; } function buy6TokensTo(address to) external payable returns (bool) { uint256 paidAmount = msg.value; require(paidAmount == (_tokenPrice * 5 + _tokenPrice / 2), "Invalid amount for token purchase"); // price for 6 tokens is 5.5 times the price for one token uint256 nextToken = nextTokenId(); uint256 remainingTokens = 1 + MAX_SUPPLY - nextToken; require(remainingTokens > 5, "Maximum supply already reached"); uint256 endLoop = nextToken.add(6); while (nextToken < endLoop) { _holderTokens[to].add(nextToken); _tokenOwners.set(nextToken, to); uint256 remainingA = MAX_A - _countA; bool a = (uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now, nextToken))) % remainingTokens) < remainingA; uint8 pow = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), now + 1, nextToken))) % (a ? 21 : 79) + (a ? 80 : 1)); _additionalData[nextToken] = AdditionalData(a, false, pow); if (a) { _countA = _countA + 1; } emit Transfer(address(0), to, nextToken); nextToken = nextToken.add(1); remainingTokens = remainingTokens.sub(1); } _nextId = _nextId.add(6); payable(owner()).transfer(paidAmount); return true; } /** * @dev Retrieves if the specified token is of A type. */ function isA(uint256 tokenId) external view returns (bool) { require(_exists(tokenId), "Token ID does not exist"); return _additionalData[tokenId].isA; } /** * @dev Retrieves if the specified token has its someBool attribute set. */ function someBool(uint256 tokenId) external view returns (bool) { require(_exists(tokenId), "Token ID does not exist"); return _additionalData[tokenId].someBool; } /** * @dev Sets someBool for the specified token. Can only be used by the owner of the token (not an approved account). * Owner needs to also own a ticket token to set the someBool attribute. */ function setSomeBool(uint256 tokenId, bool newValue) external { require(_exists(tokenId), "Token ID does not exist"); require(ownerOf(tokenId) == msg.sender, "Only token owner can set attribute"); _additionalData[tokenId].someBool = newValue; } /** * @dev Retrieves the power value for a specified token. */ function power(uint256 tokenId) external view returns (uint8) { require(_exists(tokenId), "Token ID does not exist"); return _additionalData[tokenId].power; } // owner functions: /** * @dev Function to set the base URI for all token IDs. It is automatically added as a prefix to the token id in {tokenURI} to retrieve the token URI. */ function setBaseURI(string calldata baseURI_) external onlyOwner { _baseURI = baseURI_; } /** * @dev Sets a new token price. */ function setTokenPrice(uint256 newPrice) external onlyOwner { _tokenPrice = newPrice; } function setFreeBoolSetter(address holder, bool setForFree) external onlyOwner { freeBoolSetters[holder] = setForFree; } // internal functions: /** * @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) private { _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`). */ function _exists(uint256 tokenId) private view returns (bool) { return tokenId < _nextId && _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) private view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev 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`. * - contract owner must have transfer globally allowed. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) private { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } } contract NFTeGG_Proxy_2 is Context, Ownable, ERC20Recoverable, ERC721Recoverable{ using SafeMath for uint256; using SafeERC20 for IERC20; T1 public T1_ADDRESS = T1(0x10a7ecF97c46e3229fE1B801a5943153762e0cF0); // address of NFT contract (ERC721) address public T3_ADDRESS = address(0xD821E91DB8aED33641ac5D122553cf10de49c8eF); // address of eFAME contract (ERC20) used for distributing rewards uint256 public balance = 0; uint256 public reward = 100*1E18; uint256 public counter = 300; uint256 public repay = 150*1E18; uint256 public eFAMEprice = 1250*1E18; uint256 public eGGprice = T1_ADDRESS.tokenPrice(); function setReward(uint256 newreward) external onlyOwner { reward = newreward; } function seteGGprice(uint256 neweGG) external onlyOwner { eGGprice = neweGG; } function setRepay(uint256 newrepay) external onlyOwner { repay = newrepay; } function setEprice(uint256 neweprice) external onlyOwner { eFAMEprice = neweprice; } function sendETH(uint256 value) external onlyOwner { balance -= value; msg.sender.transfer(value); } function sendeFAME(uint256 value) external onlyOwner { IERC20(T3_ADDRESS).safeTransfer(msg.sender, value); } function buyTokenRef(address buyer, address ref) external payable returns (bool) { T1_ADDRESS.buyTokenTo{gas: 230000, value: msg.value}(buyer); uint256 eFAMEBalance = IERC20(T3_ADDRESS).balanceOf(address(this)); if (buyer != ref) { if (eFAMEBalance >= (reward)){ uint256 pay = reward; IERC20(T3_ADDRESS).safeTransfer(ref, pay);}} } function buy6TokenRef(address buyer, address ref) external payable returns (bool) { T1_ADDRESS.buy6TokensTo{gas: 1000000, value: msg.value}(buyer); uint256 eFAMEBalance = IERC20(T3_ADDRESS).balanceOf(address(this)); if (buyer != ref) { if (eFAMEBalance >= (reward*6)){ uint256 pay = reward*6; IERC20(T3_ADDRESS).safeTransfer(ref, pay);}} } function shareNFTeGG(uint256 tokenid) external { address user = msg.sender; bool NFTeGGApproved = IERC721(T1_ADDRESS).isApprovedForAll(user, address(this)); uint256 eFAMEBalance = IERC20(T3_ADDRESS).balanceOf(address(this)); require(NFTeGGApproved == true, "Please approve Contract,before sharing a NFTeGG."); require(eFAMEBalance >= repay, "Contract dont have enough eFAME."); address randomish = address(uint160(uint(keccak256(abi.encodePacked(counter, blockhash(block.number)))))); counter += 1; IERC20(T3_ADDRESS).safeTransfer(user, repay); IERC721(T1_ADDRESS).transferFrom(user, address(randomish), tokenid); } function setT1(address newT1_ADDRESS) external onlyOwner { T1_ADDRESS = T1(newT1_ADDRESS); } function setT3(address newT3_ADDRESS) external onlyOwner { T3_ADDRESS = newT3_ADDRESS; } function ETHtoContract() public payable { //msg.value is the amount of wei that the msg.sender sent with this transaction. //If the transaction doesn't fail, then the contract now has this ETH. balance += msg.value; } function buyeGGeFAME() external { address user = msg.sender; uint256 eFAMEBalance = IERC20(T3_ADDRESS).balanceOf(address(user)); uint256 eFAMEAllowance = IERC20(T3_ADDRESS).allowance(user, address(this)); require(balance >= eGGprice, "Contract out of ETH, please Contact NFTeGG Support."); require(eFAMEBalance >= eFAMEprice, "You dont have enough eFAME."); require(eFAMEAllowance >= eFAMEprice, "You dont have enough eFAME allowance."); IERC20(T3_ADDRESS).safeTransferFrom(user, address(this), eFAMEprice); T1_ADDRESS.buyTokenTo{gas: 230000, value: (eGGprice)}(user); balance -= eGGprice; } function buyeGG6eFAME() external { address user = msg.sender; uint256 eFAMEBalance = IERC20(T3_ADDRESS).balanceOf(address(user)); uint256 eFAMEAllowance = IERC20(T3_ADDRESS).allowance(user, address(this)); uint256 price = ((eGGprice*5)+(eGGprice/2)); require(balance >= price, "Contract out of ETH, please try 1 eGG."); require(eFAMEBalance >= price, "You dont have enough eFAME."); require(eFAMEAllowance >= price, "You dont have enough eFAME allowance."); IERC20(T3_ADDRESS).safeTransferFrom(user, address(this), ((eFAMEprice*6))); T1_ADDRESS.buy6TokensTo{gas: 1000000, value: price}(user); balance -= price; } }
Used to approve the recovery of stuck token, also in future./
function recoverERC721ApproveAll(address token, address recipient, bool approved) external onlyOwner { return IERC721(token).setApprovalForAll(recipient, approved); }
1,094,356
pragma solidity ^0.4.24; // File: ..\openzeppelin-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 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&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: ..\openzeppelin-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 OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } // File: ..\openzeppelin-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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts\HorseyExchange.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { 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 transferFrom(address _from, address _to, uint256 _tokenId) public; } /** @dev HorseyExchange contract - handles horsey market exchange which includes the following set of functions: 1. Deposit to Exchange 2. Cancel sale 3. Purchase token **/ contract HorseyExchange is Pausable { //also Ownable using SafeMath for uint256; event HorseyDeposit(uint256 tokenId, uint256 price); event SaleCanceled(uint256 tokenId); event HorseyPurchased(uint256 tokenId, address newOwner, uint256 totalToPay); /// @dev Fee applied to market maker - measured as percentage uint256 public marketMakerFee = 3; /// @dev Amount collected in fees uint256 collectedFees = 0; /// @dev RoyalStables TOKEN ERC721Basic public token; /** @dev used to store the price and the owner address of a token on sale */ struct SaleData { uint256 price; address owner; } /// @dev Market spec to lookup price and original owner based on token id mapping (uint256 => SaleData) market; /// @dev mapping of current tokens on market by owner mapping (address => uint256[]) userBarn; /// @dev initialize constructor() Pausable() public { } /** @dev Since the exchange requires the horsey contract and horsey contract requires exchange address, we cant initialize both of them in constructors @param _token Address of the stables contract */ function setStables(address _token) external onlyOwner() { require(address(_token) != 0,"Address of token is zero"); token = ERC721Basic(_token); } /** @dev Allows the owner to change market fees @param fees The new fees to apply (can be zero) */ function setMarketFees(uint256 fees) external onlyOwner() { marketMakerFee = fees; } /// @return the tokens on sale based on the user address function getTokensOnSale(address user) external view returns(uint256[]) { return userBarn[user]; } /// @return the token price with the fees function getTokenPrice(uint256 tokenId) public view isOnMarket(tokenId) returns (uint256) { return market[tokenId].price + (market[tokenId].price.div(100).mul(marketMakerFee)); } /** @dev User sends token to sell to exchange - at this point the exchange contract takes ownership, but will map token ownership back to owner for auotmated withdraw on cancel - requires that user is the rightful owner and is not asking for a null price */ function depositToExchange(uint256 tokenId, uint256 price) external whenNotPaused() isTokenOwner(tokenId) nonZeroPrice(price) tokenAvailable() { require(token.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer"); //Transfers token from depositee to exchange (contract address) token.transferFrom(msg.sender, address(this), tokenId); //add the token to the market market[tokenId] = SaleData(price,msg.sender); //Add token to exchange map - tracking by owner of all tokens userBarn[msg.sender].push(tokenId); emit HorseyDeposit(tokenId, price); } /** @dev Allows true owner of token to cancel sale at anytime @param tokenId ID of the token to remove from the market @return true if user still has tokens for sale */ function cancelSale(uint256 tokenId) external whenNotPaused() originalOwnerOf(tokenId) tokenAvailable() returns (bool) { //throws on fail - transfers token from exchange back to original owner token.transferFrom(address(this),msg.sender,tokenId); //Reset token on market - remove delete market[tokenId]; //Reset barn tracker for user _removeTokenFromBarn(tokenId, msg.sender); emit SaleCanceled(tokenId); //Return true if this user is still &#39;active&#39; within the exchange //This will help with client side actions return userBarn[msg.sender].length > 0; } /** @dev Performs the purchase of a token that is present on the market - this includes checking that the proper amount is sent + appliced fee, updating seller&#39;s balance, updated collected fees and transfering token to buyer Only market tokens can be purchased @param tokenId ID of the token we wish to purchase */ function purchaseToken(uint256 tokenId) external payable whenNotPaused() isOnMarket(tokenId) tokenAvailable() notOriginalOwnerOf(tokenId) { //Did the sender accidently pay over? - if so track the amount over uint256 totalToPay = getTokenPrice(tokenId); require(msg.value >= totalToPay, "Not paying enough"); //fetch this tokens sale data SaleData memory sale = market[tokenId]; //Add to collected fee amount payable to DEVS collectedFees += totalToPay - sale.price; //pay the seller sale.owner.transfer(sale.price); //Reset barn tracker for user _removeTokenFromBarn(tokenId, sale.owner); //Reset token on market - remove delete market[tokenId]; //Transfer the ERC721 to the buyer - we leave the sale amount //to be withdrawn by the user (transferred from exchange) token.transferFrom(address(this), msg.sender, tokenId); //Return over paid amount to sender if necessary if(msg.value > totalToPay) //overpaid { msg.sender.transfer(msg.value.sub(totalToPay)); } emit HorseyPurchased(tokenId, msg.sender, totalToPay); } /// @dev Transfers the collected fees to the owner function withdraw() external onlyOwner() { assert(collectedFees <= address(this).balance); owner.transfer(collectedFees); collectedFees = 0; } /** @dev Internal function to remove a token from the users barn array @param tokenId ID of the token to remove @param barnAddress Address of the user selling tokens */ function _removeTokenFromBarn(uint tokenId, address barnAddress) internal { uint256[] storage barnArray = userBarn[barnAddress]; require(barnArray.length > 0,"No tokens to remove"); int index = _indexOf(tokenId, barnArray); require(index >= 0, "Token not found in barn"); // Shift entire array :( for (uint256 i = uint256(index); i<barnArray.length-1; i++){ barnArray[i] = barnArray[i+1]; } // Remove element, update length, return array // this should be enough since https://ethereum.stackexchange.com/questions/1527/how-to-delete-an-element-at-a-certain-index-in-an-array barnArray.length--; } /** @dev Helper function which stores in memory an array which is passed in, and @param item element we are looking for @param array the array to look into @return the index of the item of interest */ function _indexOf(uint item, uint256[] memory array) internal pure returns (int256){ //Iterate over array to find indexOf(token) for(uint256 i = 0; i < array.length; i++){ if(array[i] == item){ return int256(i); } } //Item not found return -1; } /// @dev requires token to be on the market = current owner is exchange modifier isOnMarket(uint256 tokenId) { require(token.ownerOf(tokenId) == address(this),"Token not on market"); _; } /// @dev Is the user the owner of this token? modifier isTokenOwner(uint256 tokenId) { require(token.ownerOf(tokenId) == msg.sender,"Not tokens owner"); _; } /// @dev Is this the original owner of the token - at exchange level modifier originalOwnerOf(uint256 tokenId) { require(market[tokenId].owner == msg.sender,"Not the original owner of"); _; } /// @dev Is this the original owner of the token - at exchange level modifier notOriginalOwnerOf(uint256 tokenId) { require(market[tokenId].owner != msg.sender,"Is the original owner"); _; } /// @dev Is a nonzero price being sent? modifier nonZeroPrice(uint256 price){ require(price > 0,"Price is zero"); _; } /// @dev Do we have a token address modifier tokenAvailable(){ require(address(token) != 0,"Token address not set"); _; } } // File: contracts\EthorseHelpers.sol contract BettingControllerInterface { address public owner; } /** @title Race contract - used for linking ethorse Race struct @dev This interface is losely based on ethorse race contract */ contract EthorseRace { //Encapsulation of racing information struct chronus_info { bool betting_open; // boolean: check if betting is open bool race_start; //boolean: check if race has started bool race_end; //boolean: check if race has ended bool voided_bet; //boolean: check if race has been voided uint32 starting_time; // timestamp of when the race starts uint32 betting_duration; uint32 race_duration; // duration of the race uint32 voided_timestamp; } address public owner; //Point to racing information chronus_info public chronus; //Coin index mapping to flag - true if index is winner mapping (bytes32 => bool) public winner_horse; /* // exposing the coin pool details for DApp function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint) { return (coinIndex[index].total, coinIndex[index].pre, coinIndex[index].post, coinIndex[index].price_check, voterIndex[candidate].bets[index]); } */ // exposing the coin pool details for DApp function getCoinIndex(bytes32 index, address candidate) external constant returns (uint, uint, uint, bool, uint); } /** @title API contract - used to connect with Race contract and encapsulate race information for token inidices and winner checking. */ contract EthorseHelpers { /// @dev Convert all symbols to bytes array bytes32[] public all_horses = [bytes32("BTC"),bytes32("ETH"),bytes32("LTC")]; mapping(address => bool) private _legitOwners; /// @dev Used to add new symbol to the bytes array function _addHorse(bytes32 newHorse) internal { all_horses.push(newHorse); } function _addLegitOwner(address newOwner) internal { _legitOwners[newOwner] = true; } function getall_horsesCount() public view returns(uint) { return all_horses.length; } /** @param raceAddress - address of this race @param eth_address - user&#39;s ethereum wallet address @return true if user is winner + name of the winning horse (LTC,BTC,ETH,...) */ function _isWinnerOf(address raceAddress, address eth_address) internal view returns (bool,bytes32) { //acquire race, fails if doesnt exist EthorseRace race = EthorseRace(raceAddress); //acquire races betting controller BettingControllerInterface bc = BettingControllerInterface(race.owner()); //make sure the betting controllers owner is in the legit list given by devs require(_legitOwners[bc.owner()]); //acquire chronus bool voided_bet; //boolean: check if race has been voided bool race_end; //boolean: check if race has ended (,,race_end,voided_bet,,,,) = race.chronus(); //cant be winner if race was refunded or didnt end yet if(voided_bet || !race_end) return (false,bytes32(0)); //aquire winner race index bytes32 horse; bool found = false; uint256 arrayLength = all_horses.length; //Iterate over coin symbols to find winner - tie could be possible? for(uint256 i = 0; i < arrayLength; i++) { if(race.winner_horse(all_horses[i])) { horse = all_horses[i]; found = true; break; } } //no winner horse? shouldnt happen unless this horse isnt registered if(!found) return (false,bytes32(0)); //check the bet amount of the eth_address on the winner horse uint256 bet_amount = 0; if(eth_address != address(0)) { (,,,, bet_amount) = race.getCoinIndex(horse, eth_address); } //winner if the eth_address had a bet > 0 on the winner horse return (bet_amount > 0, horse); } } // File: contracts\HorseyToken.sol contract RoyalStablesInterface { struct Horsey { address race; bytes32 dna; uint8 feedingCounter; uint8 tier; } mapping(uint256 => Horsey) public horseys; mapping(address => uint32) public carrot_credits; mapping(uint256 => string) public names; address public master; function getOwnedTokens(address eth_address) public view returns (uint256[]); function storeName(uint256 tokenId, string newName) public; function storeCarrotsCredit(address client, uint32 amount) public; function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public; function modifyHorseyDna(uint256 tokenId, bytes32 dna) public; function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public; function modifyHorseyTier(uint256 tokenId, uint8 tier) public; function unstoreHorsey(uint256 tokenId) public; function ownerOf(uint256 tokenId) public returns (address); } /** @title HorseyToken ERC721 Token @dev Horse contract - horse derives fro AccessManager built on top of ERC721 token and uses @dev EthorseHelpers and AccessManager */ contract HorseyToken is EthorseHelpers,Pausable { using SafeMath for uint256; /// @dev called when someone claims a token event Claimed(address raceAddress, address eth_address, uint256 tokenId); /// @dev called when someone starts a feeding process event Feeding(uint256 tokenId); /// @dev called when someone ends a feeding process event ReceivedCarrot(uint256 tokenId, bytes32 newDna); /// @dev called when someone fails to end a feeding on the 255 blocks timer event FeedingFailed(uint256 tokenId); /// @dev called when a horsey is renamed event HorseyRenamed(uint256 tokenId, string newName); /// @dev called when a horsey is freed for carrots event HorseyFreed(uint256 tokenId); /// @dev address of the RoyalStables RoyalStablesInterface public stables; ///@dev multiplier applied to carrots received from burning a horsey uint8 public carrotsMultiplier = 1; ///@dev multiplier applied to rarity bounds when feeding horsey uint8 public rarityMultiplier = 1; ///@dev fee to pay when claiming a token uint256 public claimingFee = 0.008 ether; /** @dev Holds the necessary data to feed a horsey The user has to create begin feeding and wait for the block with the feeding transaction to be hashed Only then he can stop the feeding */ struct FeedingData { uint256 blockNumber; ///@dev Holds the block number where the feeding began uint256 horsey; ///@dev Holds the horsey id } /// @dev Maps a user to his pending feeding mapping(address => FeedingData) public pendingFeedings; /// @dev Stores the renaming fees per character a user has to pay upon renaming a horsey uint256 public renamingCostsPerChar = 0.001 ether; /** @dev Contracts constructor Initializes token data is pausable,ownable @param stablesAddress Address of the official RoyalStables contract */ constructor(address stablesAddress) EthorseHelpers() Pausable() public { stables = RoyalStablesInterface(stablesAddress); } /** @dev Changes multiplier for rarity on feed @param newRarityMultiplier The cost to charge in wei for each character of the name */ function setRarityMultiplier(uint8 newRarityMultiplier) external onlyOwner() { rarityMultiplier = newRarityMultiplier; } /** @dev Sets a new muliplier for freeing a horse @param newCarrotsMultiplier the new multiplier for feeding */ function setCarrotsMultiplier(uint8 newCarrotsMultiplier) external onlyOwner() { carrotsMultiplier = newCarrotsMultiplier; } /** @dev Sets a new renaming per character cost in wei Any CLevel can call this function @param newRenamingCost The cost to charge in wei for each character of the name */ function setRenamingCosts(uint256 newRenamingCost) external onlyOwner() { renamingCostsPerChar = newRenamingCost; } /** @dev Sets a new claiming fee in wei Any CLevel can call this function @param newClaimingFee The cost to charge in wei for each claimed HRSY */ function setClaimingCosts(uint256 newClaimingFee) external onlyOwner() { claimingFee = newClaimingFee; } /** @dev Allows to add a legit owner address for races validation @param newAddress the dev address deploying BettingController to add */ function addLegitDevAddress(address newAddress) external onlyOwner() { _addLegitOwner(newAddress); } /** @dev Owner can withdraw the current balance */ function withdraw() external onlyOwner() { owner.transfer(address(this).balance); //throws on fail } //allows owner to add a horse name to the possible horses list (BTC,ETH,LTC,...) /** @dev Adds a new horse index to the possible horses list (BTC,ETH,LTC,...) This is in case ethorse adds a new coin Any CLevel can call this function @param newHorse Index of the horse to add (same data type as the original ethorse erc20 contract code) */ function addHorseIndex(bytes32 newHorse) external onlyOwner() { _addHorse(newHorse); } /** @dev Gets the complete list of token ids which belongs to an address @param eth_address The address you want to lookup owned tokens from @return List of all owned by eth_address tokenIds */ function getOwnedTokens(address eth_address) public view returns (uint256[]) { return stables.getOwnedTokens(eth_address); } /** @dev Allows to check if an eth_address can claim a horsey from this contract should we also check if already claimed here? @param raceAddress The ethorse race you want to claim from @param eth_address The users address you want to claim the token for @return True only if eth_address is a winner of the race contract at raceAddress */ function can_claim(address raceAddress, address eth_address) public view returns (bool) { bool res; (res,) = _isWinnerOf(raceAddress, eth_address); return res; } /** @dev Allows a user to claim a special horsey with the same dna as the race one Cant be used on paused The sender has to be a winner of the race and must never have claimed a special horsey from this race @param raceAddress The race&#39;s address */ function claim(address raceAddress) external payable costs(claimingFee) whenNotPaused() { //call _isWinnerOf with a 0 address to simply get the winner horse bytes32 winner; (,winner) = _isWinnerOf(raceAddress, address(0)); require(winner != bytes32(0),"Winner is zero"); require(can_claim(raceAddress, msg.sender),"can_claim return false"); //require(!exists(id)); should already be checked by mining function uint256 id = _generate_special_horsey(raceAddress, msg.sender, winner); emit Claimed(raceAddress, msg.sender, id); } /** @dev Allows a user to give a horsey a name or rename it This function is payable and its cost is renamingCostsPerChar * length(newname) Cant be called while paused If called with too low balance, the modifier will throw If called with too much balance, we try to return the remaining funds back Upon completion we update all ceos balances, maybe not very efficient? @param tokenId ID of the horsey to rename @param newName The name to give to the horsey */ function renameHorsey(uint256 tokenId, string newName) external whenNotPaused() onlyOwnerOf(tokenId) costs(renamingCostsPerChar * bytes(newName).length) payable { uint256 renamingFee = renamingCostsPerChar * bytes(newName).length; //Return over paid amount to sender if necessary if(msg.value > renamingFee) //overpaid { msg.sender.transfer(msg.value.sub(renamingFee)); } //store the new name stables.storeName(tokenId,newName); emit HorseyRenamed(tokenId,newName); } /** @dev Allows a user to burn a token he owns to get carrots The mount of carrots given is equal to the horsey&#39;s feedingCounter upon burning Cant be called on a horsey with a pending feeding Cant be called while paused @param tokenId ID of the token to burn */ function freeForCarrots(uint256 tokenId) external whenNotPaused() onlyOwnerOf(tokenId) { require(pendingFeedings[msg.sender].horsey != tokenId,""); //credit carrots uint8 feedingCounter; (,,feedingCounter,) = stables.horseys(tokenId); stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) + uint32(feedingCounter * carrotsMultiplier)); stables.unstoreHorsey(tokenId); emit HorseyFreed(tokenId); } /** @dev Returns the amount of carrots the user owns We have a getter to hide the carrots amount from public view @return The current amount of carrot credits the sender owns */ function getCarrotCredits() external view returns (uint32) { return stables.carrot_credits(msg.sender); } /** @dev Returns horsey data of a given token @param tokenId ID of the horsey to fetch @return (race address, dna, feedingCounter, name) */ function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string) { RoyalStablesInterface.Horsey memory temp; (temp.race,temp.dna,temp.feedingCounter,temp.tier) = stables.horseys(tokenId); return (temp.race,temp.dna,temp.feedingCounter,stables.names(tokenId)); } /** @dev Allows to feed a horsey to increase its feedingCounter value Gives a chance to get a rare trait The amount of carrots required is the value of current feedingCounter The carrots the user owns will be reduced accordingly upon success Cant be called while paused @param tokenId ID of the horsey to feed */ function feed(uint256 tokenId) external whenNotPaused() onlyOwnerOf(tokenId) carrotsMeetLevel(tokenId) noFeedingInProgress() { pendingFeedings[msg.sender] = FeedingData(block.number,tokenId); uint8 feedingCounter; (,,feedingCounter,) = stables.horseys(tokenId); stables.storeCarrotsCredit(msg.sender,stables.carrot_credits(msg.sender) - uint32(feedingCounter)); emit Feeding(tokenId); } /** @dev Allows user to stop feeding a horsey This will trigger a random rarity chance */ function stopFeeding() external feedingInProgress() returns (bool) { uint256 blockNumber = pendingFeedings[msg.sender].blockNumber; uint256 tokenId = pendingFeedings[msg.sender].horsey; //you cant feed and stop feeding from the same block! require(block.number - blockNumber >= 1,"feeding and stop feeding are in same block"); delete pendingFeedings[msg.sender]; //solidity only gives you access to the previous 256 blocks //deny and remove this obsolete feeding if we cant fetch its blocks hash if(block.number - blockNumber > 255) { //the feeding is outdated = failed //the user can feed again but he lost his carrots emit FeedingFailed(tokenId); return false; } //token could have been transfered in the meantime to someone else if(stables.ownerOf(tokenId) != msg.sender) { //the feeding is failed because the token no longer belongs to this user = failed //the user has lost his carrots emit FeedingFailed(tokenId); return false; } //call horsey generation with the claim block hash _feed(tokenId, blockhash(blockNumber)); bytes32 dna; (,dna,,) = stables.horseys(tokenId); emit ReceivedCarrot(tokenId, dna); return true; } /// @dev Only ether sent explicitly through the donation() function is accepted function() external payable { revert("Not accepting donations"); } /** @dev Internal function to increase a horsey&#39;s rarity Uses a random value to assess if the feeding process increases rarity The chances of having a rarity increase are based on the current feedingCounter @param tokenId ID of the token to "feed" @param blockHash Hash of the block where the feeding began */ function _feed(uint256 tokenId, bytes32 blockHash) internal { //Grab the upperbound for probability 100,100 uint8 tier; uint8 feedingCounter; (,,feedingCounter,tier) = stables.horseys(tokenId); uint256 probabilityByRarity = 10 ** (uint256(tier).add(1)); uint256 randNum = uint256(keccak256(abi.encodePacked(tokenId, blockHash))) % probabilityByRarity; //Scale probability based on horsey&#39;s level if(randNum <= (feedingCounter * rarityMultiplier)){ _increaseRarity(tokenId, blockHash); } //Increment feedingCounter //Maximum allowed is 255, which requires 32385 carrots, so we should never reach that if(feedingCounter < 255) { stables.modifyHorseyFeedingCounter(tokenId,feedingCounter+1); } } /// @dev creates a special token id based on the race and the coin index function _makeSpecialId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(race, sender, coinIndex))); } /** @dev Internal function to generate a SPECIAL horsey token we then use the ERC721 inherited minting process the dna is a bytes32 target for a keccak256. Not using blockhash finaly, a bitmask zeros the first 2 bytes for rarity traits @param race Address of the associated race @param eth_address Address of the user to receive the token @param coinIndex The index of the winning coin @return ID of the token */ function _generate_special_horsey(address race, address eth_address, bytes32 coinIndex) internal returns (uint256) { uint256 id = _makeSpecialId(race, eth_address, coinIndex); //generate dna bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16); //storeHorsey checks if the token exists before minting already, so we dont have to here stables.storeHorsey(eth_address,id,race,dna,1,0); return id; } /** @dev Internal function called to increase a horsey rarity We generate a random zeros mask with a single 1 in the leading 16 bits @param tokenId Id of the token to increase rarity of @param blockHash hash of the block where the feeding began */ function _increaseRarity(uint256 tokenId, bytes32 blockHash) private { uint8 tier; bytes32 dna; (,dna,,tier) = stables.horseys(tokenId); if(tier < 255) stables.modifyHorseyTier(tokenId,tier+1); uint256 random = uint256(keccak256(abi.encodePacked(tokenId, blockHash))); //this creates a mask of 256 bits such as one of the first 16 bits will be 1 bytes32 rarityMask = _shiftLeft(bytes32(1), (random % 16 + 240)); bytes32 newdna = dna | rarityMask; //apply mask to add the random flag stables.modifyHorseyDna(tokenId,newdna); } /// @dev shifts a bytes32 left by n positions function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) { return bytes32(uint256(data)*(2 ** n)); } /// @dev shifts a bytes32 right by n positions function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) { return bytes32(uint256(data)/(2 ** n)); } /// @dev Modifier to ensure user can afford a rehorse modifier carrotsMeetLevel(uint256 tokenId){ uint256 feedingCounter; (,,feedingCounter,) = stables.horseys(tokenId); require(feedingCounter <= stables.carrot_credits(msg.sender),"Not enough carrots"); _; } /// @dev insures the caller payed the required amount modifier costs(uint256 amount) { require(msg.value >= amount,"Not enough funds"); _; } /// @dev requires the address to be non null modifier validAddress(address addr) { require(addr != address(0),"Address is zero"); _; } /// @dev requires that the user isnt feeding a horsey already modifier noFeedingInProgress() { //if the key does not exit, then the default struct data is used where blockNumber is 0 require(pendingFeedings[msg.sender].blockNumber == 0,"Already feeding"); _; } /// @dev requires that the user isnt feeding a horsey already modifier feedingInProgress() { //if the key does not exit, then the default struct data is used where blockNumber is 0 require(pendingFeedings[msg.sender].blockNumber != 0,"No pending feeding"); _; } /// @dev requires that the user isnt feeding a horsey already modifier onlyOwnerOf(uint256 tokenId) { require(stables.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token"); _; } } // File: contracts\HorseyPilot.sol /** @title Adds rank management utilities and voting behavior @dev Handles equities distribution and levels of access EXCHANGE FUNCTIONS IT CAN CALL setClaimingFee OK 5 setMarketFees OK 1 withdraw TOKEN FUNCTIONS IT CAN CALL setRenamingCosts OK 0 addHorseIndex OK 3 setCarrotsMultiplier 8 setRarityMultiplier 9 addLegitDevAddress 2 withdraw PAUSING OK 4 */ contract HorseyPilot { using SafeMath for uint256; /// @dev event that is fired when a new proposal is made event NewProposal(uint8 methodId, uint parameter, address proposer); /// @dev event that is fired when a proposal is accepted event ProposalPassed(uint8 methodId, uint parameter, address proposer); /// @dev minimum threshold that must be met in order to confirm /// a contract update uint8 constant votingThreshold = 2; /// @dev minimum amount of time a proposal can live /// after this time it can be forcefully invoked or killed by anyone uint256 constant proposalLife = 7 days; /// @dev amount of time until another proposal can be made /// we use this to eliminate proposal spamming uint256 constant proposalCooldown = 1 days; /// @dev used to reference the exact time the last proposal vetoed uint256 cooldownStart; /// @dev The addresses of the accounts (or contracts) that can execute actions within each roles. address public jokerAddress; address public knightAddress; address public paladinAddress; /// @dev List of all addresses allowed to vote address[3] public voters; /// @dev joker is the pool and gets the rest uint8 constant public knightEquity = 40; uint8 constant public paladinEquity = 10; /// @dev deployed exchange and token addresses address public exchangeAddress; address public tokenAddress; /// @dev Mapping to keep track of pending balance of contract owners mapping(address => uint) internal _cBalance; /// @dev Encapsulates information about a proposed update struct Proposal{ address proposer; /// @dev address of the CEO at the origin of this proposal uint256 timestamp; /// @dev the time at which this propsal was made uint256 parameter; /// @dev parameters associated with proposed method invocation uint8 methodId; /// @dev id maps to function 0:rename horse, 1:change fees, 2:? address[] yay; /// @dev list of all addresses who voted address[] nay; /// @dev list of all addresses who voted against } /// @dev the pending proposal Proposal public currentProposal; /// @dev true if the proposal is waiting for votes bool public proposalInProgress = false; /// @dev Value to keep track of avaible balance uint256 public toBeDistributed; /// @dev used to deploy contracts only once bool deployed = false; /** @param _jokerAddress joker @param _knightAddress knight @param _paladinAddress paladin @param _voters list of all allowed voting addresses */ constructor( address _jokerAddress, address _knightAddress, address _paladinAddress, address[3] _voters ) public { jokerAddress = _jokerAddress; knightAddress = _knightAddress; paladinAddress = _paladinAddress; for(uint i = 0; i < 3; i++) { voters[i] = _voters[i]; } //Set cooldown start to 1 day ago so that cooldown is irrelevant cooldownStart = block.timestamp - proposalCooldown; } /** @dev Used to deploy children contracts as a one shot call */ function deployChildren(address stablesAddress) external { require(!deployed,"already deployed"); // deploy token and exchange contracts exchangeAddress = new HorseyExchange(); tokenAddress = new HorseyToken(stablesAddress); // the exchange requires horsey token address HorseyExchange(exchangeAddress).setStables(stablesAddress); deployed = true; } /** @dev Transfers joker ownership to a new address @param newJoker the new address */ function transferJokerOwnership(address newJoker) external validAddress(newJoker) { require(jokerAddress == msg.sender,"Not right role"); _moveBalance(newJoker); jokerAddress = newJoker; } /** @dev Transfers knight ownership to a new address @param newKnight the new address */ function transferKnightOwnership(address newKnight) external validAddress(newKnight) { require(knightAddress == msg.sender,"Not right role"); _moveBalance(newKnight); knightAddress = newKnight; } /** @dev Transfers paladin ownership to a new address @param newPaladin the new address */ function transferPaladinOwnership(address newPaladin) external validAddress(newPaladin) { require(paladinAddress == msg.sender,"Not right role"); _moveBalance(newPaladin); paladinAddress = newPaladin; } /** @dev Allow CEO to withdraw from pending value always checks to update redist We ONLY redist when a user tries to withdraw so we are not redistributing on every payment @param destination The address to send the ether to */ function withdrawCeo(address destination) external onlyCLevelAccess() validAddress(destination) { //Check that pending balance can be redistributed - if so perform //this procedure if(toBeDistributed > 0){ _updateDistribution(); } //Grab the balance of this CEO uint256 balance = _cBalance[msg.sender]; //If we have non-zero balance, CEO may withdraw from pending amount if(balance > 0 && (address(this).balance >= balance)) { destination.transfer(balance); //throws on fail _cBalance[msg.sender] = 0; } } /// @dev acquire funds from owned contracts function syncFunds() external { uint256 prevBalance = address(this).balance; HorseyToken(tokenAddress).withdraw(); HorseyExchange(exchangeAddress).withdraw(); uint256 newBalance = address(this).balance; //add to toBeDistributed = toBeDistributed.add(newBalance - prevBalance); } /// @dev allows a noble to access his holdings function getNobleBalance() external view onlyCLevelAccess() returns (uint256) { return _cBalance[msg.sender]; } /** @dev Make a proposal and add to pending proposals @param methodId a string representing the function ie. &#39;renameHorsey()&#39; @param parameter parameter to be used if invocation is approved */ function makeProposal( uint8 methodId, uint256 parameter ) external onlyCLevelAccess() proposalAvailable() cooledDown() { currentProposal.timestamp = block.timestamp; currentProposal.parameter = parameter; currentProposal.methodId = methodId; currentProposal.proposer = msg.sender; delete currentProposal.yay; delete currentProposal.nay; proposalInProgress = true; emit NewProposal(methodId,parameter,msg.sender); } /** @dev Call to vote on a pending proposal */ function voteOnProposal(bool voteFor) external proposalPending() onlyVoters() notVoted() { //cant vote on expired! require((block.timestamp - currentProposal.timestamp) <= proposalLife); if(voteFor) { currentProposal.yay.push(msg.sender); //Proposal went through? invoke it if( currentProposal.yay.length >= votingThreshold ) { _doProposal(); proposalInProgress = false; //no need to reset cooldown on successful proposal return; } } else { currentProposal.nay.push(msg.sender); //Proposal failed? if( currentProposal.nay.length >= votingThreshold ) { proposalInProgress = false; cooldownStart = block.timestamp; return; } } } /** @dev Helps moving pending balance from one role to another @param newAddress the address to transfer the pending balance from the msg.sender account */ function _moveBalance(address newAddress) internal validAddress(newAddress) { require(newAddress != msg.sender); /// @dev IMPORTANT or else the account balance gets reset here! _cBalance[newAddress] = _cBalance[msg.sender]; _cBalance[msg.sender] = 0; } /** @dev Called at the start of withdraw to distribute any pending balances that live in the contract will only ever be called if balance is non-zero (funds should be distributed) */ function _updateDistribution() internal { require(toBeDistributed != 0,"nothing to distribute"); uint256 knightPayday = toBeDistributed.div(100).mul(knightEquity); uint256 paladinPayday = toBeDistributed.div(100).mul(paladinEquity); /// @dev due to the equities distribution, queen gets the remaining value uint256 jokerPayday = toBeDistributed.sub(knightPayday).sub(paladinPayday); _cBalance[jokerAddress] = _cBalance[jokerAddress].add(jokerPayday); _cBalance[knightAddress] = _cBalance[knightAddress].add(knightPayday); _cBalance[paladinAddress] = _cBalance[paladinAddress].add(paladinPayday); //Reset balance to 0 toBeDistributed = 0; } /** @dev Execute the proposal */ function _doProposal() internal { /// UPDATE the renaming cost if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); /// UPDATE the market fees if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); /// UPDATE the legit dev addresses list if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitDevAddress(address(currentProposal.parameter)); /// ADD a horse index to exchange if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); /// PAUSE/UNPAUSE the dApp if( currentProposal.methodId == 4 ) { if(currentProposal.parameter == 0) { HorseyExchange(exchangeAddress).unpause(); HorseyToken(tokenAddress).unpause(); } else { HorseyExchange(exchangeAddress).pause(); HorseyToken(tokenAddress).pause(); } } /// UPDATE the claiming fees if( currentProposal.methodId == 5 ) HorseyToken(tokenAddress).setClaimingCosts(currentProposal.parameter); /// UPDATE carrots multiplier if( currentProposal.methodId == 8 ){ HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); } /// UPDATE rarity multiplier if( currentProposal.methodId == 9 ){ HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); } emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); } /// @dev requires the address to be non null modifier validAddress(address addr) { require(addr != address(0),"Address is zero"); _; } /// @dev requires the sender to be on the contract owners list modifier onlyCLevelAccess() { require((jokerAddress == msg.sender) || (knightAddress == msg.sender) || (paladinAddress == msg.sender),"not c level"); _; } /// @dev requires that a proposal is not in process or has exceeded its lifetime, and has cooled down /// after being vetoed modifier proposalAvailable(){ require(((!proposalInProgress) || ((block.timestamp - currentProposal.timestamp) > proposalLife)),"proposal already pending"); _; } // @dev requries that if this proposer was the last proposer, that he or she has reached the // cooldown limit modifier cooledDown( ){ if(msg.sender == currentProposal.proposer && (block.timestamp - cooldownStart < 1 days)){ revert("Cool down period not passed yet"); } _; } /// @dev requires a proposal to be active modifier proposalPending() { require(proposalInProgress,"no proposal pending"); _; } /// @dev requires the voter to not have voted already modifier notVoted() { uint256 length = currentProposal.yay.length; for(uint i = 0; i < length; i++) { if(currentProposal.yay[i] == msg.sender) { revert("Already voted"); } } length = currentProposal.nay.length; for(i = 0; i < length; i++) { if(currentProposal.nay[i] == msg.sender) { revert("Already voted"); } } _; } /// @dev requires the voter to not have voted already modifier onlyVoters() { bool found = false; uint256 length = voters.length; for(uint i = 0; i < length; i++) { if(voters[i] == msg.sender) { found = true; break; } } if(!found) { revert("not a voter"); } _; } }
/ UPDATE the renaming cost UPDATE the market fees UPDATE the legit dev addresses list ADD a horse index to exchange PAUSE/UNPAUSE the dApp UPDATE carrots multiplier UPDATE rarity multiplier
function _doProposal() internal { if( currentProposal.methodId == 0 ) HorseyToken(tokenAddress).setRenamingCosts(currentProposal.parameter); if( currentProposal.methodId == 1 ) HorseyExchange(exchangeAddress).setMarketFees(currentProposal.parameter); if( currentProposal.methodId == 2 ) HorseyToken(tokenAddress).addLegitDevAddress(address(currentProposal.parameter)); if( currentProposal.methodId == 3 ) HorseyToken(tokenAddress).addHorseIndex(bytes32(currentProposal.parameter)); if( currentProposal.methodId == 4 ) { if(currentProposal.parameter == 0) { HorseyExchange(exchangeAddress).unpause(); HorseyToken(tokenAddress).unpause(); HorseyExchange(exchangeAddress).pause(); HorseyToken(tokenAddress).pause(); } } if( currentProposal.methodId == 8 ){ HorseyToken(tokenAddress).setCarrotsMultiplier(uint8(currentProposal.parameter)); } if( currentProposal.methodId == 9 ){ HorseyToken(tokenAddress).setRarityMultiplier(uint8(currentProposal.parameter)); } emit ProposalPassed(currentProposal.methodId,currentProposal.parameter,currentProposal.proposer); }
2,309,550
pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;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; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { revert(); } _; } 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) onlyPayloadSize(2 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @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 Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * 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 ) onlyPayloadSize(3 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev 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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev 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, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint _value) whenNotPaused public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) whenNotPaused public returns (bool) { return super.transferFrom(_from, _to, _value); } } contract MXAContract is PausableToken { string public constant name = "MXAContract"; string public constant symbol = "MXCA"; uint8 public constant decimals = 18; address public ico = address(0xc5f35d49b25fBC5fd15cc08a8ED2425b973A9115); address public community = address(0x570c67B61551EbBAf282f081D5fB699Ab26810E1); address public team = address(0x8a383f8d648B199D2A16C160624D1332ecF96486); address public foundation = address(0x702b595E76B30088845a4e469c09822324aCF663); constructor() public { totalSupply_ = 30 * (10 ** 8) * (10 ** uint256(decimals)); //发行总量 30亿 balances[ico] = totalSupply_ * 30 / 100; //基石+私募+公募 30% balances[community] = totalSupply_ * 30 / 100; //社区生态 30% balances[team] = totalSupply_ * 20 / 100; //团队 20% balances[foundation] = totalSupply_ * 20 / 100; //基金会 20% emit Transfer(address(0), ico, balances[ico]); emit Transfer(address(0), community, balances[community]); emit Transfer(address(0), team, balances[team]); emit Transfer(address(0), foundation, balances[foundation]); } function batchTransfer(address[] _receivers, uint _value) whenNotPaused public { uint cnt = _receivers.length; require(cnt>0 && _value>=0); for(uint i=0; i<cnt; i++){ address _to = _receivers[i]; require(_to!=address(0) && _value<=balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); } } function batchTransfers(address[] _receivers, uint[] _values) whenNotPaused public { uint cnt = _receivers.length; require(cnt>0 && cnt==_values.length); for(uint i=0; i<cnt; i++){ address _to = _receivers[i]; uint _value = _values[i]; require(_to!=address(0) && _value>=0 && _value<=balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_values[i]); balances[_to] = balances[_to].add(_values[i]); emit Transfer(msg.sender, _to, _values[i]); } } // Send back ether sent to me function () external { revert(); } }
Transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
6,728,477
pragma solidity ^0.6.1; pragma experimental ABIEncoderV2; import "./IBusinessPartnerStorage.sol"; import "./IEternalStorage.sol"; import "./IAddressRegistry.sol"; import "./Ownable.sol"; import "./Bindable.sol"; import "./StringConvertible.sol"; contract BusinessPartnerStorage is IBusinessPartnerStorage, Ownable, Bindable, StringConvertible { // Client is hashed into every key to avoid collisions with other contracts using the same eternal storage string constant private CLIENT = "BpStorage"; // Seller Id string constant private SELLER_ID = "sellerId"; string constant private SELLER_DESC = "sellerDescription"; string constant private CONTRACT_ADDRESS = "contractAddress"; string constant private APPROVER_ADDRESS = "approverAddress"; string constant private IS_ACTIVE = "isActive"; IEternalStorage public eternalStorage; IAddressRegistry public addressRegistry; constructor (address contractAddressOfRegistry) public { addressRegistry = IAddressRegistry(contractAddressOfRegistry); } /// Configure contract /// @param nameOfEternalStorage key of the entry in the address registry that holds the eternal storage contract address function configure(string memory nameOfEternalStorage) onlyOwner() override public { // Eternal storage eternalStorage = IEternalStorage(addressRegistry.getAddressString(nameOfEternalStorage)); require(address(eternalStorage) != address(0), "Could not find EternalStorage address in registry"); } function getSeller(bytes32 sellerId) override external view returns (IPoTypes.Seller memory seller) { seller.sellerId = eternalStorage.getBytes32Value(keccak256(abi.encodePacked(CLIENT, sellerId, SELLER_ID))); seller.sellerDescription = eternalStorage.getBytes32Value(keccak256(abi.encodePacked(CLIENT, sellerId, SELLER_DESC))); seller.contractAddress = eternalStorage.getAddressValue(keccak256(abi.encodePacked(CLIENT, sellerId, CONTRACT_ADDRESS))); seller.approverAddress = eternalStorage.getAddressValue(keccak256(abi.encodePacked(CLIENT, sellerId, APPROVER_ADDRESS))); seller.isActive = eternalStorage.getBooleanValue(keccak256(abi.encodePacked(CLIENT, sellerId, IS_ACTIVE))); } function setSeller(IPoTypes.Seller calldata seller) onlyRegisteredCaller() override external { eternalStorage.setBytes32Value(keccak256(abi.encodePacked(CLIENT, seller.sellerId, SELLER_ID)), seller.sellerId); eternalStorage.setBytes32Value(keccak256(abi.encodePacked(CLIENT, seller.sellerId, SELLER_DESC)), seller.sellerDescription); eternalStorage.setAddressValue(keccak256(abi.encodePacked(CLIENT, seller.sellerId, CONTRACT_ADDRESS)), seller.contractAddress); eternalStorage.setAddressValue(keccak256(abi.encodePacked(CLIENT, seller.sellerId, APPROVER_ADDRESS)), seller.approverAddress); eternalStorage.setBooleanValue(keccak256(abi.encodePacked(CLIENT, seller.sellerId, IS_ACTIVE)), seller.isActive); } }
Configure contract nameOfEternalStorage key of the entry in the address registry that holds the eternal storage contract address Eternal storage
function configure(string memory nameOfEternalStorage) onlyOwner() override public { eternalStorage = IEternalStorage(addressRegistry.getAddressString(nameOfEternalStorage)); require(address(eternalStorage) != address(0), "Could not find EternalStorage address in registry"); }
894,345
// SPDX-License-Identifier: MIT pragma solidity >=0.8.9; /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivFixedPointOverflow(uint256 prod1); /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator); /// @notice Emitted when one of the inputs is type(int256).min. error PRBMath__MulDivSignedInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows int256. error PRBMath__MulDivSignedOverflow(uint256 rAbs); /// @notice Emitted when the input is MIN_SD59x18. error PRBMathSD59x18__AbsInputTooSmall(); /// @notice Emitted when ceiling a number overflows SD59x18. error PRBMathSD59x18__CeilOverflow(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__DivInputTooSmall(); /// @notice Emitted when one of the intermediary unsigned results overflows SD59x18. error PRBMathSD59x18__DivOverflow(uint256 rAbs); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathSD59x18__ExpInputTooBig(int256 x); /// @notice Emitted when the input is greater than 192. error PRBMathSD59x18__Exp2InputTooBig(int256 x); /// @notice Emitted when flooring a number underflows SD59x18. error PRBMathSD59x18__FloorUnderflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18. error PRBMathSD59x18__FromIntOverflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18. error PRBMathSD59x18__FromIntUnderflow(int256 x); /// @notice Emitted when the product of the inputs is negative. error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y); /// @notice Emitted when multiplying the inputs overflows SD59x18. error PRBMathSD59x18__GmOverflow(int256 x, int256 y); /// @notice Emitted when the input is less than or equal to zero. error PRBMathSD59x18__LogInputTooSmall(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__MulInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__MulOverflow(uint256 rAbs); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__PowuOverflow(uint256 rAbs); /// @notice Emitted when the input is negative. error PRBMathSD59x18__SqrtNegativeInput(int256 x); /// @notice Emitted when the calculating the square root overflows SD59x18. error PRBMathSD59x18__SqrtOverflow(int256 x); /// @notice Emitted when addition overflows UD60x18. error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y); /// @notice Emitted when ceiling a number overflows UD60x18. error PRBMathUD60x18__CeilOverflow(uint256 x); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathUD60x18__ExpInputTooBig(uint256 x); /// @notice Emitted when the input is greater than 192. error PRBMathUD60x18__Exp2InputTooBig(uint256 x); /// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18. error PRBMathUD60x18__FromUintOverflow(uint256 x); /// @notice Emitted when multiplying the inputs overflows UD60x18. error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y); /// @notice Emitted when the input is less than 1. error PRBMathUD60x18__LogInputTooSmall(uint256 x); /// @notice Emitted when the calculating the square root overflows UD60x18. error PRBMathUD60x18__SqrtOverflow(uint256 x); /// @notice Emitted when subtraction underflows UD60x18. error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y); /// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library /// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point /// representation. When it does not, it is explicitly mentioned in the NatSpec documentation. library PRBMath { /// STRUCTS /// struct SD59x18 { int256 value; } struct UD60x18 { uint256 value; } /// STORAGE /// /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @dev Largest power of two divisor of SCALE. uint256 internal constant SCALE_LPOTD = 262144; /// @dev SCALE inverted mod 2^256. uint256 internal constant SCALE_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /// FUNCTIONS /// /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Has to use 192.64-bit fixed-point numbers. /// See https://ethereum.stackexchange.com/a/96594/24693. /// @param x The exponent as an unsigned 192.64-bit fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp2(uint256 x) internal pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows // because the initial result is 2^191 and all magic factors are less than 2^65. if (x & 0x8000000000000000 > 0) { result = (result * 0x16A09E667F3BCC909) >> 64; } if (x & 0x4000000000000000 > 0) { result = (result * 0x1306FE0A31B7152DF) >> 64; } if (x & 0x2000000000000000 > 0) { result = (result * 0x1172B83C7D517ADCE) >> 64; } if (x & 0x1000000000000000 > 0) { result = (result * 0x10B5586CF9890F62A) >> 64; } if (x & 0x800000000000000 > 0) { result = (result * 0x1059B0D31585743AE) >> 64; } if (x & 0x400000000000000 > 0) { result = (result * 0x102C9A3E778060EE7) >> 64; } if (x & 0x200000000000000 > 0) { result = (result * 0x10163DA9FB33356D8) >> 64; } if (x & 0x100000000000000 > 0) { result = (result * 0x100B1AFA5ABCBED61) >> 64; } if (x & 0x80000000000000 > 0) { result = (result * 0x10058C86DA1C09EA2) >> 64; } if (x & 0x40000000000000 > 0) { result = (result * 0x1002C605E2E8CEC50) >> 64; } if (x & 0x20000000000000 > 0) { result = (result * 0x100162F3904051FA1) >> 64; } if (x & 0x10000000000000 > 0) { result = (result * 0x1000B175EFFDC76BA) >> 64; } if (x & 0x8000000000000 > 0) { result = (result * 0x100058BA01FB9F96D) >> 64; } if (x & 0x4000000000000 > 0) { result = (result * 0x10002C5CC37DA9492) >> 64; } if (x & 0x2000000000000 > 0) { result = (result * 0x1000162E525EE0547) >> 64; } if (x & 0x1000000000000 > 0) { result = (result * 0x10000B17255775C04) >> 64; } if (x & 0x800000000000 > 0) { result = (result * 0x1000058B91B5BC9AE) >> 64; } if (x & 0x400000000000 > 0) { result = (result * 0x100002C5C89D5EC6D) >> 64; } if (x & 0x200000000000 > 0) { result = (result * 0x10000162E43F4F831) >> 64; } if (x & 0x100000000000 > 0) { result = (result * 0x100000B1721BCFC9A) >> 64; } if (x & 0x80000000000 > 0) { result = (result * 0x10000058B90CF1E6E) >> 64; } if (x & 0x40000000000 > 0) { result = (result * 0x1000002C5C863B73F) >> 64; } if (x & 0x20000000000 > 0) { result = (result * 0x100000162E430E5A2) >> 64; } if (x & 0x10000000000 > 0) { result = (result * 0x1000000B172183551) >> 64; } if (x & 0x8000000000 > 0) { result = (result * 0x100000058B90C0B49) >> 64; } if (x & 0x4000000000 > 0) { result = (result * 0x10000002C5C8601CC) >> 64; } if (x & 0x2000000000 > 0) { result = (result * 0x1000000162E42FFF0) >> 64; } if (x & 0x1000000000 > 0) { result = (result * 0x10000000B17217FBB) >> 64; } if (x & 0x800000000 > 0) { result = (result * 0x1000000058B90BFCE) >> 64; } if (x & 0x400000000 > 0) { result = (result * 0x100000002C5C85FE3) >> 64; } if (x & 0x200000000 > 0) { result = (result * 0x10000000162E42FF1) >> 64; } if (x & 0x100000000 > 0) { result = (result * 0x100000000B17217F8) >> 64; } if (x & 0x80000000 > 0) { result = (result * 0x10000000058B90BFC) >> 64; } if (x & 0x40000000 > 0) { result = (result * 0x1000000002C5C85FE) >> 64; } if (x & 0x20000000 > 0) { result = (result * 0x100000000162E42FF) >> 64; } if (x & 0x10000000 > 0) { result = (result * 0x1000000000B17217F) >> 64; } if (x & 0x8000000 > 0) { result = (result * 0x100000000058B90C0) >> 64; } if (x & 0x4000000 > 0) { result = (result * 0x10000000002C5C860) >> 64; } if (x & 0x2000000 > 0) { result = (result * 0x1000000000162E430) >> 64; } if (x & 0x1000000 > 0) { result = (result * 0x10000000000B17218) >> 64; } if (x & 0x800000 > 0) { result = (result * 0x1000000000058B90C) >> 64; } if (x & 0x400000 > 0) { result = (result * 0x100000000002C5C86) >> 64; } if (x & 0x200000 > 0) { result = (result * 0x10000000000162E43) >> 64; } if (x & 0x100000 > 0) { result = (result * 0x100000000000B1721) >> 64; } if (x & 0x80000 > 0) { result = (result * 0x10000000000058B91) >> 64; } if (x & 0x40000 > 0) { result = (result * 0x1000000000002C5C8) >> 64; } if (x & 0x20000 > 0) { result = (result * 0x100000000000162E4) >> 64; } if (x & 0x10000 > 0) { result = (result * 0x1000000000000B172) >> 64; } if (x & 0x8000 > 0) { result = (result * 0x100000000000058B9) >> 64; } if (x & 0x4000 > 0) { result = (result * 0x10000000000002C5D) >> 64; } if (x & 0x2000 > 0) { result = (result * 0x1000000000000162E) >> 64; } if (x & 0x1000 > 0) { result = (result * 0x10000000000000B17) >> 64; } if (x & 0x800 > 0) { result = (result * 0x1000000000000058C) >> 64; } if (x & 0x400 > 0) { result = (result * 0x100000000000002C6) >> 64; } if (x & 0x200 > 0) { result = (result * 0x10000000000000163) >> 64; } if (x & 0x100 > 0) { result = (result * 0x100000000000000B1) >> 64; } if (x & 0x80 > 0) { result = (result * 0x10000000000000059) >> 64; } if (x & 0x40 > 0) { result = (result * 0x1000000000000002C) >> 64; } if (x & 0x20 > 0) { result = (result * 0x10000000000000016) >> 64; } if (x & 0x10 > 0) { result = (result * 0x1000000000000000B) >> 64; } if (x & 0x8 > 0) { result = (result * 0x10000000000000006) >> 64; } if (x & 0x4 > 0) { result = (result * 0x10000000000000003) >> 64; } if (x & 0x2 > 0) { result = (result * 0x10000000000000001) >> 64; } if (x & 0x1 > 0) { result = (result * 0x10000000000000001) >> 64; } // We're doing two things at the same time: // // 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for // the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191 // rather than 192. // 2. Convert the result to the unsigned 60.18-decimal fixed-point format. // // This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n". result *= SCALE; result >>= (191 - (x >> 64)); } } /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// @param x The uint256 number for which to find the index of the most significant bit. /// @return msb The index of the most significant bit as an uint256. function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; } if (x >= 2**16) { x >>= 16; msb += 16; } if (x >= 2**8) { x >>= 8; msb += 8; } if (x >= 2**4) { x >>= 4; msb += 4; } if (x >= 2**2) { x >>= 2; msb += 2; } if (x >= 2**1) { // No need to shift x any more. msb += 1; } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Requirements: /// - The denominator cannot be zero. /// - The result must fit within uint256. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The multiplicand as an uint256. /// @param y The multiplier as an uint256. /// @param denominator The divisor as an uint256. /// @return result The result as an uint256. function mulDiv( 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 PRBMath__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; } } /// @notice Calculates floor(x*y÷1e18) with full precision. /// /// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of /// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717. /// /// Requirements: /// - The result must fit within uint256. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations: /// 1. x * y = type(uint256).max * SCALE /// 2. (x * y) % SCALE >= SCALE / 2 /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 >= SCALE) { revert PRBMath__MulDivFixedPointOverflow(prod1); } uint256 remainder; uint256 roundUpUnit; assembly { remainder := mulmod(x, y, SCALE) roundUpUnit := gt(remainder, 499999999999999999) } if (prod1 == 0) { unchecked { result = (prod0 / SCALE) + roundUpUnit; return result; } } assembly { result := add( mul( or( div(sub(prod0, remainder), SCALE_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1)) ), SCALE_INVERSE ), roundUpUnit ) } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - None of the inputs can be type(int256).min. /// - The result must fit within int256. /// /// @param x The multiplicand as an int256. /// @param y The multiplier as an int256. /// @param denominator The divisor as an int256. /// @return result The result as an int256. function mulDivSigned( int256 x, int256 y, int256 denominator ) internal pure returns (int256 result) { if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) { revert PRBMath__MulDivSignedInputTooSmall(); } // Get hold of the absolute values of x, y and the denominator. uint256 ax; uint256 ay; uint256 ad; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); ad = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of (x*y)÷denominator. The result must fit within int256. uint256 rAbs = mulDiv(ax, ay, ad); if (rAbs > uint256(type(int256).max)) { revert PRBMath__MulDivSignedOverflow(rAbs); } // Get the signs of x, y and the denominator. uint256 sx; uint256 sy; uint256 sd; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) sd := sgt(denominator, sub(0, 1)) } // XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs. // If yes, the result should be negative. result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs); } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as an uint256. function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Set the initial guess to the least power of two that is greater than or equal to sqrt(x). uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } } } /// @title PRBMathSD59x18 /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18 /// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have /// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers /// are bound by the minimum and the maximum values permitted by the Solidity type int256. library PRBMathSD59x18 { /// @dev log2(e) as a signed 59.18-decimal fixed-point number. int256 internal constant LOG2_E = 1_442695040888963407; /// @dev Half the SCALE number. int256 internal constant HALF_SCALE = 5e17; /// @dev The maximum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967; /// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev The minimum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968; /// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev How many trailing decimals can be represented. int256 internal constant SCALE = 1e18; /// INTERNAL FUNCTIONS /// /// @notice Calculate the absolute value of x. /// /// @dev Requirements: /// - x must be greater than MIN_SD59x18. /// /// @param x The number to calculate the absolute value for. /// @param result The absolute value of x. function abs(int256 x) internal pure returns (int256 result) { unchecked { if (x == MIN_SD59x18) { revert PRBMathSD59x18__AbsInputTooSmall(); } result = x < 0 ? -x : x; } } /// @notice Calculates the arithmetic average of x and y, rounding down. /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The arithmetic average as a signed 59.18-decimal fixed-point number. function avg(int256 x, int256 y) internal pure returns (int256 result) { // The operations can never overflow. unchecked { int256 sum = (x >> 1) + (y >> 1); if (sum < 0) { // If at least one of x and y is odd, we add 1 to the result. This is because shifting negative numbers to the // right rounds down to infinity. assembly { result := add(sum, and(or(x, y), 1)) } } else { // If both x and y are odd, we add 1 to the result. This is because if both numbers are odd, the 0.5 // remainder gets truncated twice. result = sum + (x & y & 1); } } } /// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to MAX_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number. function ceil(int256 x) internal pure returns (int256 result) { if (x > MAX_WHOLE_SD59x18) { revert PRBMathSD59x18__CeilOverflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x > 0) { result += SCALE; } } } } /// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - All from "PRBMath.mulDiv". /// - None of the inputs can be MIN_SD59x18. /// - The denominator cannot be zero. /// - The result must fit within int256. /// /// Caveats: /// - All from "PRBMath.mulDiv". /// /// @param x The numerator as a signed 59.18-decimal fixed-point number. /// @param y The denominator as a signed 59.18-decimal fixed-point number. /// @param result The quotient as a signed 59.18-decimal fixed-point number. function div(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__DivInputTooSmall(); } // Get hold of the absolute values of x and y. uint256 ax; uint256 ay; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); } // Compute the absolute value of (x*SCALE)÷y. The result must fit within int256. uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__DivOverflow(rAbs); } // Get the signs of x and y. uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } // XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result // should be positive. Otherwise, it should be negative. result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } /// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (int256 result) { result = 2_718281828459045235; } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the insight that e^x = 2^(x * log2(e)). /// /// Requirements: /// - All from "log2". /// - x must be less than 133.084258667509499441. /// /// Caveats: /// - All from "exp2". /// - For any x less than -41.446531673892822322, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp(int256 x) internal pure returns (int256 result) { // Without this check, the value passed to "exp2" would be less than -59.794705707972522261. if (x < -41_446531673892822322) { return 0; } // Without this check, the value passed to "exp2" would be greater than 192. if (x >= 133_084258667509499441) { revert PRBMathSD59x18__ExpInputTooBig(x); } // Do the fixed-point multiplication inline to save gas. unchecked { int256 doubleScaleProduct = x * LOG2_E; result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 192 or less. /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - For any x less than -59.794705707972522261, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp2(int256 x) internal pure returns (int256 result) { // This works because 2^(-x) = 1/2^x. if (x < 0) { // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero. if (x < -59_794705707972522261) { return 0; } // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. unchecked { result = 1e36 / exp2(-x); } } else { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (x >= 192e18) { revert PRBMathSD59x18__Exp2InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE); // Safe to convert the result to int256 directly because the maximum input allowed is 192. result = int256(PRBMath.exp2(x192x64)); } } } /// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be greater than or equal to MIN_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number. function floor(int256 x) internal pure returns (int256 result) { if (x < MIN_WHOLE_SD59x18) { revert PRBMathSD59x18__FloorUnderflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x < 0) { result -= SCALE; } } } } /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right /// of the radix point for negative numbers. /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part /// @param x The signed 59.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as a signed 59.18-decimal fixed-point number. function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } } /// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation. /// /// @dev Requirements: /// - x must be greater than or equal to MIN_SD59x18 divided by SCALE. /// - x must be less than or equal to MAX_SD59x18 divided by SCALE. /// /// @param x The basic integer to convert. /// @param result The same number in signed 59.18-decimal fixed-point representation. function fromInt(int256 x) internal pure returns (int256 result) { unchecked { if (x < MIN_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntUnderflow(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntOverflow(x); } result = x * SCALE; } } /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within MAX_SD59x18, lest it overflows. /// - x * y cannot be negative. /// /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function gm(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { return 0; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. int256 xy = x * y; if (xy / x != y) { revert PRBMathSD59x18__GmOverflow(x, y); } // The product cannot be negative. if (xy < 0) { revert PRBMathSD59x18__GmNegativeProduct(x, y); } // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE // during multiplication. See the comments within the "sqrt" function. result = int256(PRBMath.sqrt(uint256(xy))); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as a signed 59.18-decimal fixed-point number. function inv(int256 x) internal pure returns (int256 result) { unchecked { // 1e36 is SCALE * SCALE. result = 1e36 / x; } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the insight that ln(x) = log2(x) / log2(e). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as a signed 59.18-decimal fixed-point number. function ln(int256 x) internal pure returns (int256 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 195205294292027477728. unchecked { result = (log2(x) * SCALE) / LOG2_E; } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the insight that log10(x) = log2(x) / log2(10). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as a signed 59.18-decimal fixed-point number. function log10(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } // Note that the "mul" in this block is the assembly mul operation, not the "mul" function defined in this contract. // prettier-ignore assembly { switch x case 1 { result := mul(SCALE, sub(0, 18)) } case 10 { result := mul(SCALE, sub(1, 18)) } case 100 { result := mul(SCALE, sub(2, 18)) } case 1000 { result := mul(SCALE, sub(3, 18)) } case 10000 { result := mul(SCALE, sub(4, 18)) } case 100000 { result := mul(SCALE, sub(5, 18)) } case 1000000 { result := mul(SCALE, sub(6, 18)) } case 10000000 { result := mul(SCALE, sub(7, 18)) } case 100000000 { result := mul(SCALE, sub(8, 18)) } case 1000000000 { result := mul(SCALE, sub(9, 18)) } case 10000000000 { result := mul(SCALE, sub(10, 18)) } case 100000000000 { result := mul(SCALE, sub(11, 18)) } case 1000000000000 { result := mul(SCALE, sub(12, 18)) } case 10000000000000 { result := mul(SCALE, sub(13, 18)) } case 100000000000000 { result := mul(SCALE, sub(14, 18)) } case 1000000000000000 { result := mul(SCALE, sub(15, 18)) } case 10000000000000000 { result := mul(SCALE, sub(16, 18)) } case 100000000000000000 { result := mul(SCALE, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := SCALE } case 100000000000000000000 { result := mul(SCALE, 2) } case 1000000000000000000000 { result := mul(SCALE, 3) } case 10000000000000000000000 { result := mul(SCALE, 4) } case 100000000000000000000000 { result := mul(SCALE, 5) } case 1000000000000000000000000 { result := mul(SCALE, 6) } case 10000000000000000000000000 { result := mul(SCALE, 7) } case 100000000000000000000000000 { result := mul(SCALE, 8) } case 1000000000000000000000000000 { result := mul(SCALE, 9) } case 10000000000000000000000000000 { result := mul(SCALE, 10) } case 100000000000000000000000000000 { result := mul(SCALE, 11) } case 1000000000000000000000000000000 { result := mul(SCALE, 12) } case 10000000000000000000000000000000 { result := mul(SCALE, 13) } case 100000000000000000000000000000000 { result := mul(SCALE, 14) } case 1000000000000000000000000000000000 { result := mul(SCALE, 15) } case 10000000000000000000000000000000000 { result := mul(SCALE, 16) } case 100000000000000000000000000000000000 { result := mul(SCALE, 17) } case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) } case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) } case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) } case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) } case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) } case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) } case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) } case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) } case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) } default { result := MAX_SD59x18 } } if (result == MAX_SD59x18) { // Do the fixed-point division inline to save gas. The denominator is log2(10). unchecked { result = (log2(x) * SCALE) / 3_321928094887362347; } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than zero. /// /// Caveats: /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number. function log2(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } unchecked { // This works because log2(x) = -log2(1/x). int256 sign; if (x >= SCALE) { sign = 1; } else { sign = -1; // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. assembly { x := div(1000000000000000000000000000000000000, x) } } // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE)); // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1. result = int256(n) * SCALE; // This is y = x * 2^(-n). int256 y = x >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return result * sign; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) { y = (y * y) / SCALE; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * SCALE) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result *= sign; } } /// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal /// fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers and employs constant folding, i.e. the denominator is /// always 1e18. /// /// Requirements: /// - All from "PRBMath.mulDivFixedPoint". /// - None of the inputs can be MIN_SD59x18 /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// /// @param x The multiplicand as a signed 59.18-decimal fixed-point number. /// @param y The multiplier as a signed 59.18-decimal fixed-point number. /// @return result The product as a signed 59.18-decimal fixed-point number. function mul(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__MulInputTooSmall(); } unchecked { uint256 ax; uint256 ay; ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__MulOverflow(rAbs); } uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } } /// @notice Returns PI as a signed 59.18-decimal fixed-point number. function pi() internal pure returns (int256 result) { result = 3_141592653589793238; } /// @notice Raises x to the power of y. /// /// @dev Based on the insight that x^y = 2^(log2(x) * y). /// /// Requirements: /// - All from "exp2", "log2" and "mul". /// - z cannot be zero. /// /// Caveats: /// - All from "exp2", "log2" and "mul". /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number. /// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number. /// @return result x raised to power y, as a signed 59.18-decimal fixed-point number. function pow(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { result = y == 0 ? SCALE : int256(0); } else { result = exp2(mul(log2(x), y)); } } /// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the /// famous algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - All from "abs" and "PRBMath.mulDivFixedPoint". /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - All from "PRBMath.mulDivFixedPoint". /// - Assumes 0^0 is 1. /// /// @param x The base as a signed 59.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as a signed 59.18-decimal fixed-point number. function powu(int256 x, uint256 y) internal pure returns (int256 result) { uint256 xAbs = uint256(abs(x)); // Calculate the first iteration of the loop in advance. uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE); // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. uint256 yAux = y; for (yAux >>= 1; yAux > 0; yAux >>= 1) { xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs); // Equivalent to "y % 2 == 1" but faster. if (yAux & 1 > 0) { rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs); } } // The result must fit within the 59.18-decimal fixed-point representation. if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__PowuOverflow(rAbs); } // Is the base negative and the exponent an odd number? bool isNegative = x < 0 && y & 1 == 1; result = isNegative ? -int256(rAbs) : int256(rAbs); } /// @notice Returns 1 as a signed 59.18-decimal fixed-point number. function scale() internal pure returns (int256 result) { result = SCALE; } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x cannot be negative. /// - x must be less than MAX_SD59x18 / SCALE. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as a signed 59.18-decimal fixed-point . function sqrt(int256 x) internal pure returns (int256 result) { unchecked { if (x < 0) { revert PRBMathSD59x18__SqrtNegativeInput(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__SqrtOverflow(x); } // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed // 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = int256(PRBMath.sqrt(uint256(x * SCALE))); } } /// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process. /// @param x The signed 59.18-decimal fixed-point number to convert. /// @return result The same number in basic integer form. function toInt(int256 x) internal pure returns (int256 result) { unchecked { result = x / SCALE; } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev 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 VORSafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function safeAdd(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 safeSub(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 safeMul(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 saveDiv(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 safeMod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20_Ex { /** * @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 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); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IVORCoordinator { function getProviderAddress(bytes32 _keyHash) external view returns (address); function getProviderFee(bytes32 _keyHash) external view returns (uint96); function getProviderGranularFee(bytes32 _keyHash, address _consumer) external view returns (uint96); function randomnessRequest(bytes32 keyHash, uint256 consumerSeed, uint256 feePaid) external; } /** * @title VORRequestIDBase */ contract VORRequestIDBase { /** * @notice returns the seed which is actually input to the VOR coordinator * * @dev To prevent repetition of VOR 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 VOR seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVORInputSeed( 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 _vORInputSeed The seed to be passed directly to the VOR * @return The id for this request * * @dev Note that _vORInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVORInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vORInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vORInputSeed)); } } /** * @title VORConsumerBase * @notice Interface for contracts using VOR randomness * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * to Vera the verifier in such a way that Vera can be sure he's not * making his output up to suit himself. Reggie provides Vera a public key * to which he knows the secret key. Each time Vera provides a seed to * Reggie, he gives back a value which is computed completely * deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * correctly computed once Reggie tells it to her, but without that proof, * the output is indistinguishable to her from a uniform random sample * from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * to talk to Vera the verifier about the work Reggie is doing, to provide * simple access to a verifiable source of randomness. * * @dev USAGE * * @dev Calling contracts must inherit from VORConsumerBase, and can * initialize VORConsumerBase's attributes in their constructor as * shown: * * ``` * contract VORConsumer { * constuctor(<other arguments>, address _vorCoordinator, address _xfund) * VORConsumerBase(_vorCoordinator, _xfund) public { * <initialization with other arguments goes here> * } * } * ``` * @dev The oracle will have given you an ID for the VOR keypair they have * committed to (let's call it keyHash), and have told you the minimum xFUND * price for VOR service. Make sure your contract has sufficient xFUND, and * call requestRandomness(keyHash, fee, seed), where seed is the input you * want to generate randomness from. * * @dev Once the VORCoordinator has received and validated the oracle's response * to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * makeRequestId(keyHash, seed). If your contract could have concurrent * requests open, you can use the requestId to track which seed is * associated with which randomness. See VORRequestIDBase.sol for more * details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * differ. (Which is critical to making unpredictable randomness! See the * next section.) * * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * could spoof a VOR response with any random value, so it's critical that * it cannot be directly called by anything other than this base contract * (specifically, by the VORConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * from malicious interference, it's best if you can write it so that all * behaviors implied by a VOR response are executed *during* your * fulfillRandomness method. If your contract must store the response (or * anything derived from it) and use it later, you must ensure that any * user-significant behavior which depends on that stored value cannot be * manipulated by a subsequent VOR request. * * @dev Similarly, both miners and the VOR oracle itself have some influence * over the order in which VOR responses appear on the blockchain, so if * your contract could have multiple VOR requests in flight simultaneously, * you must ensure that the order in which the VOR responses arrive cannot * be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VOR is mixed with the block hash of the * block in which the request is made, user-provided seeds have no impact * on its economic security properties. They are only included for API * compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * call is mixed into the input to the VOR *last*, a sufficiently powerful * miner could, in principle, fork the blockchain to evict the block * containing the request, forcing the request to be included in a * different block with a different hash, and therefore a different input * to the VOR. However, such an attack would incur a substantial economic * cost. This cost scales with the number of blocks the VOR oracle waits * until it calls responds to a request. */ abstract contract VORConsumerBase is VORRequestIDBase { using VORSafeMath for uint256; /** * @notice fulfillRandomness handles the VOR 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 VORConsumerBase expects its subcontracts to have a method with this * signature, and will call it once it has verified the proof * associated with the randomness. (It is triggered via a call to * rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VOR output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @notice requestRandomness initiates a request for VOR output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * by the Oracle, and verified by the vorCoordinator. * * @dev The _keyHash must already be registered with the VORCoordinator, and * the _fee must exceed the fee specified during registration of the * _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * compatibility with older versions. It can't *hurt* to mix in some of * your own randomness, here, but it's not necessary because the VOR * oracle will mix the hash of the block containing your request into the * VOR seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of xFUND to send with the request * @param _seed seed mixed into the input of the VOR. * * @return requestId unique ID for this request * * The returned requestId can be used to distinguish responses to * concurrent requests. It is passed as the first argument to * fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) internal returns (bytes32 requestId) { IVORCoordinator(vorCoordinator).randomnessRequest(_keyHash, _seed, _fee); // This is the seed passed to VORCoordinator. 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 VOR cryptographic machinery. uint256 vORSeed = makeVORInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VORCoordinator.nonces[_keyHash][this], which was incremented by the above // successful VORCoordinator.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].safeAdd(1); return makeRequestId(_keyHash, vORSeed); } /** * @notice _increaseVorCoordinatorAllowance is a helper function to increase token allowance for * the VORCoordinator * Allows this contract to increase the xFUND allowance for the VORCoordinator contract * enabling it to pay request fees on behalf of this contract. * NOTE: it is hightly recommended to wrap this around a function that uses, * for example, OpenZeppelin's onlyOwner modifier * * @param _amount uint256 amount to increase allowance by */ function _increaseVorCoordinatorAllowance(uint256 _amount) internal returns (bool) { require(xFUND.increaseAllowance(vorCoordinator, _amount), "failed to increase allowance"); return true; } /** * @notice _setVORCoordinator is a helper function to enable setting the VORCoordinator address * NOTE: it is hightly recommended to wrap this around a function that uses, * for example, OpenZeppelin's onlyOwner modifier * * @param _vorCoordinator address new VORCoordinator address */ function _setVORCoordinator(address _vorCoordinator) internal { vorCoordinator = _vorCoordinator; } address internal immutable xFUNDAddress; IERC20_Ex internal immutable xFUND; address internal vorCoordinator; // Nonces for each VOR key from which randomness has been requested. // // Must stay in sync with VORCoordinator[_keyHash][this] /* keyHash */ /* nonce */ mapping(bytes32 => uint256) private nonces; /** * @param _vorCoordinator address of VORCoordinator contract * @param _xfund address of xFUND token contract */ constructor(address _vorCoordinator, address _xfund) internal { vorCoordinator = _vorCoordinator; xFUNDAddress = _xfund; xFUND = IERC20_Ex(_xfund); } /** * @notice rawFulfillRandomness is called by VORCoordinator when it receives a valid VOR * proof. rawFulfillRandomness then calls fulfillRandomness, after validating * the origin of the call */ function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vorCoordinator, "Only VORCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } /** * @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); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // @title Base64 // @notice Provides a function for encoding some bytes in base64 // @author Brecht Devos <brecht@loopring.org> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } interface IPlayingCards { function getCardNumberAsUint(uint8 cardId) external view returns (uint8); function getCardSuitAsUint(uint8 cardId) external view returns (uint8); function getCardNumberAsStr(uint8 cardId) external view returns (string memory); function getCardSuitAsStr(uint8 cardId) external view returns (string memory); function getCardAsString(uint8 cardId) external view returns (string memory); function getCardAsSvg(uint8 cardId) external view returns (string memory); function getCardAsComponents(uint8 cardId) external view returns (uint8 number, uint8 suit); function getCardBody(uint8 numberId, uint8 suitId, uint256 fX, uint256 sX, uint256 rX) external pure returns (string memory); function getSuitPath(uint8 suitId) external pure returns (string memory); function getNumberPath(uint8 numberId) external pure returns (string memory); } contract HoldemHeroesBase is ERC721Enumerable, Ownable { // a start-hand combination struct Hand { uint8 card1; // 0 - 51 uint8 card2; // 0 - 51 } uint256 public constant MAX_NFT_SUPPLY = 1326; // final totalSupply of NFTs // sha256 hash of all generated and shuffled hands bytes32 public constant HAND_PROVENANCE = 0xbcd1a23f7cca99ec419590e58d82db68573d59d2cdf88a901c5c25edea2c075d; // start index for mapping tokenId on to handId - set during the distribution phase uint256 public startingIndex; // time after which hands are randomised and allocated to token Ids uint256 public REVEAL_TIMESTAMP; // hands have been revealed bool public REVEALED; // ranks uploaded - used only during uploadHandRanks function bool public RANKS_UPLOADED; // the block number in which the final hands were revealed uint256 public revealBlock; // IPFS hash for provenance JSON - will be set when the last hand batch is revealed string public PROVENANCE_IPFS; // array of 1326 possible start hand combinations Hand[1326] public hands; // used during reveal function to ensure batches are uploaded sequentially // according to provenance uint16 public handUploadId; uint8 public nextExpectedBatchId = 0; // mapping to ensure batch is not re-uploaded. Only used during reveal function mapping(bytes32 => bool) private isHandRevealed; // Mapping to hold hand ranks. Requires populating during contract initialisation mapping (bytes32 => uint8) public handRanks; // The playing cards contract on which HEH is built IPlayingCards public immutable playingCards; /* * EVENTS */ event BatchRevealed(uint16 startHandId, uint16 endHandId, bytes32 batchHash, uint8 batchId); event RanksInitialised(); /** * @dev constructor * @dev initialises some basic variables. * * @param _revealTimestamp uint256 - unix timestamp for when cards will be revealed and distributed * @param _playingCards address - address of Playing Cards contract */ constructor(uint256 _revealTimestamp, address _playingCards) ERC721("Holdem Heroes", "HEH") Ownable() { REVEAL_TIMESTAMP = _revealTimestamp; REVEALED = false; RANKS_UPLOADED = false; handUploadId = 0; playingCards = IPlayingCards(_playingCards); } /* * ADMIN FUNCTIONS */ /** * @dev uploadHandRanks upload the 169 start hand ranks, which are referenced * @dev by the hand getter functions. Hand ranks are stored as a mapping of a * @dev sha256 hash and the integer rank value. The hash is generated from a * @dev concatenation of the word "rank" and the hand's name. e.g. * keccak256("rankA5s") => 28 * * @param rankHashes bytes32[] array of sha256 hashes * @param ranks uint8[] array of corresponding ranks for rankHashes */ function uploadHandRanks(bytes32[] memory rankHashes, uint8[] memory ranks) external onlyOwner { require(!RANKS_UPLOADED, "uploaded"); for (uint8 i = 0; i < rankHashes.length; i++) { handRanks[rankHashes[i]] = ranks[i]; } RANKS_UPLOADED = true; emit RanksInitialised(); } /** * @dev withdrawETH allows contract owner to withdraw ether */ function withdrawETH() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /** * @dev reveal is used to upload and reveal the generated start hand combinations. * @dev hands are uploaded in batches, with each batch containing n * @dev hands. each hand is a uint8[] array of card IDs, e.g. [2, 3] * @dev with each batch represented as a 2d array of hands, for example, [[2, 3], [3, 4], ...] * @dev Batches must be uploaded sequentially according to provenance. * * @param inputs uint8[2][] batch of hands * @param batchId uint8 id of the batch being revealed * @param ipfs string IPFS hash of provenance.json. Sent with final batch only */ function reveal(uint8[2][] memory inputs, uint8 batchId, string memory ipfs) public onlyOwner { require(block.timestamp >= REVEAL_TIMESTAMP, "not yet"); require(handUploadId < 1325, "revealed"); require(batchId == nextExpectedBatchId, "seq incorrect"); bytes32 dataHash = keccak256(abi.encodePacked(inputs)); require(!isHandRevealed[dataHash], "already added"); isHandRevealed[dataHash] = true; for (uint8 i = 0; i < inputs.length; i++) { hands[handUploadId] = Hand(inputs[i][0],inputs[i][1]); handUploadId = handUploadId + 1; } emit BatchRevealed(handUploadId - uint16(inputs.length), handUploadId - 1, dataHash, batchId); if (handUploadId == 1326) { REVEALED = true; PROVENANCE_IPFS = ipfs; revealBlock = block.number; } else { nextExpectedBatchId = nextExpectedBatchId + 1; } } /* * PUBLIC GETTERS */ /** * @dev getHandShape returns the shape for a given hand ID, for example "Suited" or "s" * * @param handId uint16 ID of the hand from 0 - 1325 * @param abbreviate bool whether or not to abbreviate ("s" instead of Suited" if true) * @return string shape of hand */ function getHandShape(uint16 handId, bool abbreviate) public validHandId(handId) view returns (string memory) { uint8 card1N = playingCards.getCardNumberAsUint(hands[handId].card1); uint8 card2N = playingCards.getCardNumberAsUint(hands[handId].card2); uint8 card1S = playingCards.getCardSuitAsUint(hands[handId].card1); uint8 card2S = playingCards.getCardSuitAsUint(hands[handId].card2); if (card1N == card2N) { return abbreviate ? "" : "Pair"; } else if (card1S == card2S) { return abbreviate ? "s" : "Suited"; } else { return abbreviate ? "o" : "Offsuit"; } } /** * @dev getHandAsCardIds returns the card IDs (0 - 51) for a given hand ID, for example 12,24 * * @param handId uint16 ID of the hand from 0 - 1325 * @return card1 uint8 ID of card 1 (0 - 51) * @return card2 uint8 ID of card 2 (0 - 51) */ function getHandAsCardIds(uint16 handId) public validHandId(handId) view returns (uint8 card1, uint8 card2) { Hand storage hand = hands[handId]; if (playingCards.getCardNumberAsUint(hand.card1) > playingCards.getCardNumberAsUint(hand.card2)) { return (hand.card1, hand.card2); } else { return (hand.card2, hand.card1); } } /** * @dev getHandName returns the canonical name for a given hand ID. This is a concatenation of * @dev Card1 + Card2 + Shape, with the cards ordered by card number in descending order. * @dev E.g. A5s * * @param handId uint16 ID of the hand from 0 - 1325 * @return string hand name */ function getHandName(uint16 handId) public validHandId(handId) view returns (string memory) { string memory shape = getHandShape(handId, true); (uint8 card1, uint8 card2) = getHandAsCardIds(handId); return string(abi.encodePacked(playingCards.getCardNumberAsStr(card1), playingCards.getCardNumberAsStr(card2), shape)); } /** * @dev getHandRank returns the canonical rank for a given hand ID. Lower is better * * @param handId uint16 ID of the hand from 0 - 1325 * @return string hand rank */ function getHandRank(uint16 handId) public validHandId(handId) view returns (uint8) { return handRanks[keccak256(abi.encodePacked("rank", getHandName(handId)))]; } /** * @dev getHandAsString returns a concatenation of the card names * * @param handId uint16 ID of the hand from 0 - 1325 * @return string hand - cards names concatenated, e.g. AsAc */ function getHandAsString(uint16 handId) public validHandId(handId) view returns (string memory) { (uint8 card1, uint8 card2) = getHandAsCardIds(handId); return string(abi.encodePacked(playingCards.getCardAsString(card1), playingCards.getCardAsString(card2))); } /** * @dev getHandAsSvg returns the SVG XML for a hand, which can be rendered as an img src in a UI * * @param handId uint16 ID of the hand from 0 - 1325 * @return string SVG XML of a hand of 2 cards */ function getHandAsSvg(uint16 handId) public validHandId(handId) view returns (string memory) { (uint8 card1, uint8 card2) = getHandAsCardIds(handId); string[4] memory parts; parts[0] = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 148 62\" width=\"5in\" height=\"2.147in\">"; parts[1] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card1), playingCards.getCardSuitAsUint(card1), 7, 32, 2); parts[2] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card2), playingCards.getCardSuitAsUint(card2), 82, 107, 76); parts[3] = "</svg>"; string memory output = string( abi.encodePacked(parts[0], parts[1], parts[2], parts[3]) ); return output; } /** * @dev getHandHash returns a hand's hash, which can be used to match against the * @dev published provenance. Hand hashes can be sequentially concatenated and the * @dev concatenation itself hashed (after removing each hand hash's 0x prefix) * @dev to get the provenance hash. This provenance hash should match both the published * @dev hash and the HAND_PROVENANCE constant in this contract * * @param handId uint16 ID of the hand from 0 - 1325 * @return string hash of the hand */ function getHandHash(uint16 handId) public validHandId(handId) view returns (bytes32) { (uint8 card1, uint8 card2) = getHandAsCardIds(handId); return keccak256(abi.encodePacked( toString(handId), getHandAsString(handId), toString(card1), toString(playingCards.getCardNumberAsUint(card1)), toString(playingCards.getCardSuitAsUint(card1)), toString(card2), toString(playingCards.getCardNumberAsUint(card2)), toString(playingCards.getCardSuitAsUint(card2)) ) ); } /** * @dev tokenIdToHandId maps a given token ID onto its distributed hand ID * @dev Note - this will only run after all hands have been revealed * @dev and distributed. * * @param _tokenId uint256 ID of the NFT token from 0 - 1325 * @return uint16 hand ID associate to the token */ function tokenIdToHandId(uint256 _tokenId) public view returns (uint16) { require(_tokenId >= 0 && _tokenId < 1326, "invalid id"); require(startingIndex > 0, "not distributed"); return uint16((_tokenId + startingIndex) % MAX_NFT_SUPPLY); } /** * @dev tokenURI generates the base64 encoded JSON of the NFT itself. tokenURI will first call * @dev tokenIdToHandId to find which hand the token is for. It will then generate * @dev and output the encoded JSON containing the SVG image, name, description and * @dev attributes. * @dev Note - this will only run after all hands have been revealed * @dev and distributed. * * @param _tokenId uint256 ID of the NFT token from 0 - 1325 * @return string the token's NFT JSON */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { // we need to map the token ID onto the assigned hand ID, // based on the distribution's startingIndex. This is only available // AFTER distribution has occurred, and will return an error otherwise uint16 handId = tokenIdToHandId(_tokenId); string memory handName = getHandAsString(handId); string memory shape = getHandShape(handId, false); string memory hand = getHandName(handId); string memory rank = toString(getHandRank(handId)); string memory json = Base64.encode( bytes( string( abi.encodePacked( "{\"name\": \"", handName, "\", \"description\": \"holdemheroes.com\",", getAttributes(shape, hand, rank), "\"image\": \"data:image/svg+xml;base64,", Base64.encode(bytes(getHandAsSvg(handId))), "\"}" ) ) ) ); string memory output = string(abi.encodePacked("data:application/json;base64,", json)); return output; } /* * PRIVATE FUNCTIONS */ /** * @dev getAttributes will generate the attributes JSON for embedding into the NFT JSON * * @param shape string shape * @param hand string hand * @param rank string rank * @return string attribute JSON */ function getAttributes(string memory shape, string memory hand, string memory rank) private pure returns (string memory) { return string( abi.encodePacked( "\"attributes\": [{ \"trait_type\": \"Shape\", \"value\": \"", shape, "\"},", "{ \"trait_type\": \"Hand\", \"value\": \"", hand, "\"},", "{ \"trait_type\": \"Rank\", \"value\": \"", rank, "\"}]," ) ); } /** * @dev toString converts a given uint256 to a string. Primarily used in SVG, JSON, string name, * @dev and hash generation * * @param value uint256 number to convert * @return string number as a string */ function toString(uint256 value) private pure returns (string memory) { // Inspired by OraclizeAPI"s implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol uint256 _tmpN = value; if (_tmpN == 0) { return "0"; } uint256 temp = _tmpN; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (_tmpN != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(_tmpN % 10))); _tmpN /= 10; } return string(buffer); } /* * MODIFIERS */ /** * @dev validHandId ensures a given hand Id is valid * * @param handId uint16 id of hand */ modifier validHandId(uint16 handId) { require(handId >= 0 && handId < 1326, "invalid handId"); require(REVEALED, "not revealed"); _; } } contract HoldemHeroes is Ownable, HoldemHeroesBase, VORConsumerBase { using PRBMathSD59x18 for int256; // max number of NFTs allowed per address uint256 public MAX_PER_ADDRESS_OR_TX; // block number for when public sale opens uint256 public SALE_START_BLOCK_NUM; uint256 public basePostRevealPrice = 1 ether; /// --------------------------- /// ------- CRISP STATE ------- /// --------------------------- ///@notice block on which last purchase occurred uint256 public lastPurchaseBlock; ///@notice block on which we start decaying price uint256 public priceDecayStartBlock; ///@notice Starting EMS, before time decay. 59.18-decimal fixed-point int256 public nextPurchaseStartingEMS; ///@notice Starting price for next purchase, before time decay. 59.18-decimal fixed-point int256 public nextPurchaseStartingPrice; /// --------------------------- /// ---- CRISP PARAMETERS ----- /// --------------------------- ///@notice EMS target. 59.18-decimal fixed-point int256 public immutable targetEMS; ///@notice controls decay of sales in EMS. 59.18-decimal fixed-point int256 public immutable saleHalflife; ///@notice controls upward price movement. 59.18-decimal fixed-point int256 public immutable priceSpeed; ///@notice controls price decay. 59.18-decimal fixed-point int256 public immutable priceHalflife; /* * EVENTS */ event DistributionBegun(bytes32 requestId, address sender); event DistributionResult(bytes32 requestId, uint256 randomness, uint256 startingIndex); /** * @dev constructor * @dev initialises some basic variables. * @dev CRISP implementation from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @param _vorCoordinator address - address of VORCoordinator contract * @param _xfund address - address of xFUND contract * @param _playingCards address - address of Playing Cards contract * @param _saleStartBlockNum uint256 - block number for when pre-reveal sale starts. Allows time for card/rank init * @param _revealTimestamp uint256 - unix timestamp for when cards will be revealed and distributed * @param _maxNfts address - max number of NFTs a single wallet address can mint * @param _targetBlocksPerSale int256, e.g. 100 * @param _saleHalflife int256, e.g. 700 * @param _priceSpeed int256, e.g. 1 * @param _priceSpeedDenominator int256, e.g. 4. If _priceSpeed param is 1, final priceSpeed will be 0.25 * @param _priceHalflife int256, e.g. 100 * @param _startingPrice int256, e.g. 100 */ constructor( address _vorCoordinator, address _xfund, address _playingCards, uint256 _saleStartBlockNum, uint256 _revealTimestamp, uint256 _maxNfts, int256 _targetBlocksPerSale, int256 _saleHalflife, int256 _priceSpeed, int256 _priceSpeedDenominator, int256 _priceHalflife, int256 _startingPrice ) VORConsumerBase(_vorCoordinator, _xfund) HoldemHeroesBase(_revealTimestamp, _playingCards) { SALE_START_BLOCK_NUM = (_saleStartBlockNum > block.number) ? _saleStartBlockNum : block.number; MAX_PER_ADDRESS_OR_TX = _maxNfts; // CRISP lastPurchaseBlock = SALE_START_BLOCK_NUM; priceDecayStartBlock = SALE_START_BLOCK_NUM; // scale parameters - see https://github.com/FrankieIsLost/CRISP/blob/master/src/test/CRISP.t.sol int256 targetBlocksPerSale = PRBMathSD59x18.fromInt( _targetBlocksPerSale ); saleHalflife = PRBMathSD59x18.fromInt(_saleHalflife); priceSpeed = PRBMathSD59x18.fromInt(_priceSpeed).div(PRBMathSD59x18.fromInt(_priceSpeedDenominator)); priceHalflife = PRBMathSD59x18.fromInt(_priceHalflife); //calculate target EMS from target blocks per sale targetEMS = PRBMathSD59x18.fromInt(1).div( PRBMathSD59x18.fromInt(1) - PRBMathSD59x18.fromInt(2).pow( -targetBlocksPerSale.div(saleHalflife) ) ); nextPurchaseStartingEMS = targetEMS; nextPurchaseStartingPrice = PRBMathSD59x18.fromInt(int256(_startingPrice)); } /* * ADMIN */ /** * @dev setBasePostRevealPrice allows owner to adjust post-reveal price according to market * * @param newPrice uint256 new base price in wei */ function setBasePostRevealPrice(uint256 newPrice) external onlyOwner { basePostRevealPrice = newPrice; } /* * CRISP FUNCTIONS */ /** * @dev getCurrentEMS gets current EMS based on block number. * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @return result int256 59.18-decimal fixed-point */ function getCurrentEMS() public view returns (int256 result) { int256 blockInterval = int256(block.number - lastPurchaseBlock); blockInterval = blockInterval.fromInt(); int256 weightOnPrev = PRBMathSD59x18.fromInt(2).pow( -blockInterval.div(saleHalflife) ); result = nextPurchaseStartingEMS.mul(weightOnPrev); } /** * @dev _getNftPrice get quote for purchasing in current block, decaying price as needed. * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @return result int256 59.18-decimal fixed-point */ function _getNftPrice() internal view returns (int256 result) { if (block.number <= priceDecayStartBlock) { result = nextPurchaseStartingPrice; } //decay price if we are past decay start block else { int256 decayInterval = int256(block.number - priceDecayStartBlock) .fromInt(); int256 decay = (-decayInterval).div(priceHalflife).exp(); result = nextPurchaseStartingPrice.mul(decay); } } /** * @dev getNftPrice get quote for purchasing in current block, decaying price as needed * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @return result uint256 current price in wei */ function getNftPrice() public view returns (uint256 result) { int256 pricePerNft = _getNftPrice(); result = uint256(pricePerNft.toInt()); } /** * @dev getPostRevealNftPrice get mint price for revealed tokens, based on the hand Rank * @dev lower rank = better hand = higher price. e.g. AA = rank 1 = high price * @dev Note - this can only be used in the event that there are unminted tokens * @dev once the pre-reveal sale has ended. * * @return result uint256 price in wei */ function getPostRevealNftPrice(uint256 _tokenId) public view returns (uint256 result) { uint256 rank = uint256(getHandRank(tokenIdToHandId(_tokenId))); if(rank == 1) { result = basePostRevealPrice; } else { uint256 m = 100 - ((rank * 100) / 169); // get % as int m = (m < 10) ? 10 : m; result = (basePostRevealPrice * m) / 100; } } /** * @dev getNextStartingPriceGet starting price for next purchase before time decay * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @param lastPurchasePrice int256 last price as 59.18-decimal fixed-point * @return result int256 59.18-decimal fixed-point */ function getNextStartingPrice(int256 lastPurchasePrice) public view returns (int256 result) { int256 mismatchRatio = nextPurchaseStartingEMS.div(targetEMS); if (mismatchRatio > PRBMathSD59x18.fromInt(1)) { result = lastPurchasePrice.mul( PRBMathSD59x18.fromInt(1) + mismatchRatio.mul(priceSpeed) ); } else { result = lastPurchasePrice; } } /** * @dev getPriceDecayStartBlock Find block in which time based price decay should start * @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol * * @return result uint256 block number */ function getPriceDecayStartBlock() internal view returns (uint256 result) { int256 mismatchRatio = nextPurchaseStartingEMS.div(targetEMS); //if mismatch ratio above 1, decay should start in future if (mismatchRatio > PRBMathSD59x18.fromInt(1)) { uint256 decayInterval = uint256( saleHalflife.mul(mismatchRatio.log2()).ceil().toInt() ); result = block.number + decayInterval; } //else decay should start at the current block else { result = block.number; } } /* * MINT & DISTRIBUTION FUNCTIONS */ /** * @dev mintNFTPreReveal is a public payable function which any user can call during the pre-reveal * @dev sale phase. This allows a user to mint up to MAX_PER_ADDRESS_OR_TX tokens. Tokens are * @dev minted sequentially. Mapping of token IDs on to hand IDs (according to provenance) is * @dev executed during the reveal & distribution phase, via a call to VOR. * @dev Correct ether value is expected to pay for tokens. * * @param _numberOfNfts uint256 number of NFTs to mint in this Tx */ function mintNFTPreReveal(uint256 _numberOfNfts) external payable { uint256 numberOfNfts = (_numberOfNfts > 0) ? _numberOfNfts : 1; require(block.number >= SALE_START_BLOCK_NUM, "not started"); require(totalSupply() < MAX_NFT_SUPPLY, "sold out"); require(block.timestamp < REVEAL_TIMESTAMP, "ended"); require(numberOfNfts <= MAX_PER_ADDRESS_OR_TX, "> max per tx"); require(balanceOf(msg.sender) + numberOfNfts <= MAX_PER_ADDRESS_OR_TX, "> mint limit"); require(totalSupply() + numberOfNfts <= MAX_NFT_SUPPLY, "exceeds supply"); int256 pricePerNft = _getNftPrice(); uint256 pricePerNftScaled = uint256(pricePerNft.toInt()); uint256 totalCost = pricePerNftScaled * numberOfNfts; require(msg.value >= totalCost, "eth too low"); for (uint256 i = 0; i < numberOfNfts; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } //update CRISP state updateCrispState(pricePerNft, numberOfNfts); } /** * @dev mintNFTPostReveal is a public payable function which any user can call AFTER the pre-reveal * @dev sale phase. This allows a user to mint any available token ID that hasn't been sold yet. * @dev This function cannot be executed until hands have been revealed and distributed. * @dev Correct ether value is expected to pay for token. * * @param tokenId uint256 NFT Token ID to purchase */ function mintNFTPostReveal(uint256 tokenId) external payable { uint256 price = getPostRevealNftPrice(tokenId); require(msg.value >= price, "eth too low"); _safeMint(msg.sender, tokenId); } /** * @dev beginDistribution is called to initiate distribution and makes a VOR request to generate * @dev a random value. Can only be called after hands have been revealed according to provenance. * * @param _keyHash bytes32 key hash of the VOR Oracle that will handle the request * @param _fee uint256 xFUND fee to pay the VOR Oracle */ function beginDistribution(bytes32 _keyHash, uint256 _fee) public onlyOwner canDistribute { _increaseVorCoordinatorAllowance(_fee); bytes32 requestId = requestRandomness(_keyHash, _fee, uint256(blockhash(block.number-10))); emit DistributionBegun(requestId, msg.sender); } /** * @dev fallbackDistribution is an emergency fallback function which can be called in the event * @dev of the fulfillRandomness function failing. It can only be called by the contract owner * @dev and should only be called if beginDistribution failed. */ function fallbackDistribution() public onlyOwner canDistribute { uint256 sourceBlock = revealBlock; // Just a sanity check (EVM only stores last 256 block hashes) if (block.number - revealBlock > 255) { sourceBlock = block.number-1; } uint256 randomness = uint(blockhash(sourceBlock)); checkAndSetStartIdx(randomness); emit DistributionResult(0x0, 0, startingIndex); } /** * @dev checkAndSetStartIdx is an internal function which will take the generated randomness * @dev and calculate/set the startingIndex mapping value. * * @param _randomness uint256 generated randomness value from VOR etc. */ function checkAndSetStartIdx(uint256 _randomness) internal { // calculate based on randomness startingIndex = _randomness % (MAX_NFT_SUPPLY-1); // Prevent default sequence if (startingIndex == 0) { startingIndex = 1; } if (startingIndex > 1325) { startingIndex = 1325; } } /** * @dev fulfillRandomness is called by the VOR Oracle to fulfil the randomness request. * @dev The randomness value sent is used to calculate the start array Idx onto which * @dev hand IDs are mapped on to the NFT Token IDs. * @dev Can only be called by the correct VOR Oracle, and only via the VORCoordinator contract. * * @param _requestId bytes32 ID of the request fulfilled by the Oracle * @param _randomness uint256 the random number generated by the VOR Oracle */ function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override { require(startingIndex == 0, "already done"); checkAndSetStartIdx(_randomness); emit DistributionResult(_requestId, _randomness, startingIndex); } /** * @dev updateCrispState updates the CRISP parameters for dynamic pricing * * @param price int256 current price per NFT paid by user * @param numMinted uint256 number minted in this Tx */ function updateCrispState(int256 price, uint256 numMinted) internal { nextPurchaseStartingEMS = getCurrentEMS() + PRBMathSD59x18.fromInt(int256(numMinted)); nextPurchaseStartingPrice = getNextStartingPrice(price); priceDecayStartBlock = getPriceDecayStartBlock(); lastPurchaseBlock = block.number; } /* * MODIFIERS */ /** * @dev canDistribute checks it's time to distribute */ modifier canDistribute() { require(startingIndex == 0, "already done"); require(REVEALED, "not revealed"); _; } }
getPriceDecayStartBlock Find block in which time based price decay should start return result uint256 block number/if mismatch ratio above 1, decay should start in futureelse decay should start at the current block
function getPriceDecayStartBlock() internal view returns (uint256 result) { int256 mismatchRatio = nextPurchaseStartingEMS.div(targetEMS); if (mismatchRatio > PRBMathSD59x18.fromInt(1)) { uint256 decayInterval = uint256( saleHalflife.mul(mismatchRatio.log2()).ceil().toInt() ); result = block.number + decayInterval; } else { result = block.number; } }
13,810,348
./partial_match/1/0x9B6028ea9CC135C121bd8EAb7510ec7E19347E4E/sources/ERC20Migrator.sol
Transfers part of an account's balance in the old token to this contract, and mints the same amount of new tokens for that account. account whose tokens will be migrated amount amount of tokens to be migrated/
function migrate(address account, uint256 amount) public onlyWhitelisted { require(address(_newToken) != address(0), "ERC20Migrator: migration not started"); _legacyToken.safeTransferFrom(account, address(this), amount); _newToken.mint(account, amount); }
4,263,210
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Math } from "@openzeppelin/contracts/math/Math.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { IController } from "../../interfaces/IController.sol"; import { IIndexExchangeAdapter } from "../../interfaces/IIndexExchangeAdapter.sol"; import { Invoke } from "../lib/Invoke.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { IWETH } from "../../interfaces/external/IWETH.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; import { Position } from "../lib/Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { Uint256ArrayUtils } from "../../lib/Uint256ArrayUtils.sol"; /** * @title GeneralIndexModule * @author Set Protocol * * Smart contract that facilitates rebalances for indices. Manager can update allocation by calling startRebalance(). * There is no "end" to a rebalance, however once there are no more tokens to sell the rebalance is effectively over * until the manager calls startRebalance() again with a new allocation. Once a new allocation is passed in, allowed * traders can submit rebalance transactions by calling trade() and specifying the component they wish to rebalance. * All parameterizations for a trade are set by the manager ahead of time, including max trade size, coolOffPeriod bet- * ween trades, and exchange to trade on. WETH is used as the quote asset for all trades, near the end of rebalance * tradeRemaingingWETH() or raiseAssetTargets() can be called to clean up any excess WETH positions. Once a component's * target allocation is met any further attempted trades of that component will revert. * * SECURITY ASSUMPTION: * - Works with following modules: StreamingFeeModule, BasicIssuanceModule (any other module additions to Sets using * this module need to be examined separately) */ contract GeneralIndexModule is ModuleBase, ReentrancyGuard { using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using Position for uint256; using Math for uint256; using Position for ISetToken; using Invoke for ISetToken; using AddressArrayUtils for address[]; using AddressArrayUtils for IERC20[]; using Uint256ArrayUtils for uint256[]; /* ============ Struct ============ */ struct TradeExecutionParams { uint256 targetUnit; // Target unit of component for Set uint256 maxSize; // Max trade size in precise units uint256 coolOffPeriod; // Required time between trades for the asset uint256 lastTradeTimestamp; // Timestamp of last trade string exchangeName; // Name of exchange adapter bytes exchangeData; // Arbitrary data that can be used to encode exchange specific settings (fee tier) or features (multi-hop) } struct TradePermissionInfo { bool anyoneTrade; // Boolean indicating if anyone can execute a trade address[] tradersHistory; // Tracks permissioned traders to be deleted on module removal mapping(address => bool) tradeAllowList; // Mapping indicating which addresses are allowed to execute trade } struct RebalanceInfo { uint256 positionMultiplier; // Position multiplier at the beginning of rebalance uint256 raiseTargetPercentage; // Amount to raise all unit targets by if allowed (in precise units) address[] rebalanceComponents; // Array of components involved in rebalance } struct TradeInfo { ISetToken setToken; // Instance of SetToken IIndexExchangeAdapter exchangeAdapter; // Instance of Exchange Adapter address sendToken; // Address of token being sold address receiveToken; // Address of token being bought bool isSendTokenFixed; // Boolean indicating fixed asset is send token uint256 setTotalSupply; // Total supply of Set (in precise units) uint256 totalFixedQuantity; // Total quantity of fixed asset being traded uint256 sendQuantity; // Units of component sent to the exchange uint256 floatingQuantityLimit; // Max/min amount of floating token spent/received during trade uint256 preTradeSendTokenBalance; // Total initial balance of token being sold uint256 preTradeReceiveTokenBalance; // Total initial balance of token being bought bytes exchangeData; // Arbitrary data for executing trade on given exchange } /* ============ Events ============ */ event TradeMaximumUpdated(ISetToken indexed _setToken, address indexed _component, uint256 _newMaximum); event AssetExchangeUpdated(ISetToken indexed _setToken, address indexed _component, string _newExchangeName); event CoolOffPeriodUpdated(ISetToken indexed _setToken, address indexed _component, uint256 _newCoolOffPeriod); event ExchangeDataUpdated(ISetToken indexed _setToken, address indexed _component, bytes _newExchangeData); event RaiseTargetPercentageUpdated(ISetToken indexed _setToken, uint256 indexed _raiseTargetPercentage); event AssetTargetsRaised(ISetToken indexed _setToken, uint256 indexed positionMultiplier); event AnyoneTradeUpdated(ISetToken indexed _setToken, bool indexed _status); event TraderStatusUpdated(ISetToken indexed _setToken, address indexed _trader, bool _status); event TradeExecuted( ISetToken indexed _setToken, address indexed _sellComponent, address indexed _buyComponent, IIndexExchangeAdapter _exchangeAdapter, address _executor, uint256 _netAmountSold, uint256 _netAmountReceived, uint256 _protocolFee ); event RebalanceStarted( ISetToken indexed _setToken, address[] aggregateComponents, uint256[] aggregateTargetUnits, uint256 indexed positionMultiplier ); /* ============ Constants ============ */ uint256 private constant GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX = 0; // Id of protocol fee % assigned to this module in the Controller /* ============ State Variables ============ */ mapping(ISetToken => mapping(IERC20 => TradeExecutionParams)) public executionInfo; // Mapping of SetToken to execution parameters of each asset on SetToken mapping(ISetToken => TradePermissionInfo) public permissionInfo; // Mapping of SetToken to trading permissions mapping(ISetToken => RebalanceInfo) public rebalanceInfo; // Mapping of SetToken to relevant data for current rebalance IWETH public immutable weth; // Weth contract address /* ============ Modifiers ============ */ modifier onlyAllowedTrader(ISetToken _setToken) { _validateOnlyAllowedTrader(_setToken); _; } modifier onlyEOAIfUnrestricted(ISetToken _setToken) { _validateOnlyEOAIfUnrestricted(_setToken); _; } /* ============ Constructor ============ */ constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) { weth = _weth; } /* ============ External Functions ============ */ /** * MANAGER ONLY: Changes the target allocation of the Set, opening it up for trading by the Sets designated traders. The manager * must pass in any new components and their target units (units defined by the amount of that component the manager wants in 10**18 * units of a SetToken). Old component target units must be passed in, in the current order of the components array on the * SetToken. If a component is being removed it's index in the _oldComponentsTargetUnits should be set to 0. Additionally, the * positionMultiplier is passed in, in order to adjust the target units in the event fees are accrued or some other activity occurs * that changes the positionMultiplier of the Set. This guarantees the same relative allocation between all the components. * * @param _setToken Address of the SetToken to be rebalanced * @param _newComponents Array of new components to add to allocation * @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array * @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of * _setToken.getComponents() array, if component being removed set to 0. * @param _positionMultiplier Position multiplier when target units were calculated, needed in order to adjust target units * if fees accrued */ function startRebalance( ISetToken _setToken, address[] calldata _newComponents, uint256[] calldata _newComponentsTargetUnits, uint256[] calldata _oldComponentsTargetUnits, uint256 _positionMultiplier ) external onlyManagerAndValidSet(_setToken) { ( address[] memory aggregateComponents, uint256[] memory aggregateTargetUnits ) = _getAggregateComponentsAndUnits( _setToken.getComponents(), _newComponents, _newComponentsTargetUnits, _oldComponentsTargetUnits ); for (uint256 i = 0; i < aggregateComponents.length; i++) { require(!_setToken.hasExternalPosition(aggregateComponents[i]), "External positions not allowed"); executionInfo[_setToken][IERC20(aggregateComponents[i])].targetUnit = aggregateTargetUnits[i]; } rebalanceInfo[_setToken].rebalanceComponents = aggregateComponents; rebalanceInfo[_setToken].positionMultiplier = _positionMultiplier; emit RebalanceStarted(_setToken, aggregateComponents, aggregateTargetUnits, _positionMultiplier); } /** * ACCESS LIMITED: Calling trade() pushes the current component units closer to the target units defined by the manager in startRebalance(). * Only approved addresses can call, if anyoneTrade is false then contracts are allowed to call otherwise calling address must be EOA. * * Trade can be called at anytime but will revert if the passed component's target unit is met or cool off period hasn't passed. Trader can pass * in a max/min amount of ETH spent/received in the trade based on if the component is being bought/sold in order to prevent sandwich attacks. * The parameters defined by the manager are used to determine which exchange will be used and the size of the trade. Trade size will default * to max trade size unless the max trade size would exceed the target, then an amount that would match the target unit is traded. Protocol fees, * if enabled, are collected in the token received in a trade. * * @param _setToken Address of the SetToken * @param _component Address of SetToken component to trade * @param _ethQuantityLimit Max/min amount of ETH spent/received during trade */ function trade( ISetToken _setToken, IERC20 _component, uint256 _ethQuantityLimit ) external nonReentrant onlyAllowedTrader(_setToken) onlyEOAIfUnrestricted(_setToken) virtual { _validateTradeParameters(_setToken, _component); TradeInfo memory tradeInfo = _createTradeInfo(_setToken, _component, _ethQuantityLimit); _executeTrade(tradeInfo); uint256 protocolFee = _accrueProtocolFee(tradeInfo); (uint256 netSendAmount, uint256 netReceiveAmount) = _updatePositionStateAndTimestamp(tradeInfo, _component); emit TradeExecuted( tradeInfo.setToken, tradeInfo.sendToken, tradeInfo.receiveToken, tradeInfo.exchangeAdapter, msg.sender, netSendAmount, netReceiveAmount, protocolFee ); } /** * ACCESS LIMITED: Only callable when 1) there are no more components to be sold and, 2) entire remaining WETH amount (above WETH target) can be * traded such that resulting inflows won't exceed component's maxTradeSize nor overshoot the target unit. To be used near the end of rebalances * when a component's calculated trade size is greater in value than remaining WETH. * * Only approved addresses can call, if anyoneTrade is false then contracts are allowed to call otherwise calling address must be EOA. Trade * can be called at anytime but will revert if the passed component's target unit is met or cool off period hasn't passed. Like with trade() * a minimum component receive amount can be set. * * @param _setToken Address of the SetToken * @param _component Address of the SetToken component to trade * @param _minComponentReceived Min amount of component received during trade */ function tradeRemainingWETH( ISetToken _setToken, IERC20 _component, uint256 _minComponentReceived ) external nonReentrant onlyAllowedTrader(_setToken) onlyEOAIfUnrestricted(_setToken) virtual { require(_noTokensToSell(_setToken), "Sell other set components first"); require( executionInfo[_setToken][weth].targetUnit < _getDefaultPositionRealUnit(_setToken, weth), "WETH is below target unit" ); _validateTradeParameters(_setToken, _component); TradeInfo memory tradeInfo = _createTradeRemainingInfo(_setToken, _component, _minComponentReceived); _executeTrade(tradeInfo); uint256 protocolFee = _accrueProtocolFee(tradeInfo); (uint256 netSendAmount, uint256 netReceiveAmount) = _updatePositionStateAndTimestamp(tradeInfo, _component); require( netReceiveAmount.add(protocolFee) < executionInfo[_setToken][_component].maxSize, "Trade amount > max trade size" ); _validateComponentPositionUnit(_setToken, _component); emit TradeExecuted( tradeInfo.setToken, tradeInfo.sendToken, tradeInfo.receiveToken, tradeInfo.exchangeAdapter, msg.sender, netSendAmount, netReceiveAmount, protocolFee ); } /** * ACCESS LIMITED: For situation where all target units met and remaining WETH, uniformly raise targets by same percentage by applying * to logged positionMultiplier in RebalanceInfo struct, in order to allow further trading. Can be called multiple times if necessary, * targets are increased by amount specified by raiseAssetTargetsPercentage as set by manager. In order to reduce tracking error * raising the target by a smaller amount allows greater granularity in finding an equilibrium between the excess ETH and components * that need to be bought. Raising the targets too much could result in vastly under allocating to WETH as more WETH than necessary is * spent buying the components to meet their new target. * * @param _setToken Address of the SetToken */ function raiseAssetTargets(ISetToken _setToken) external onlyAllowedTrader(_setToken) virtual { require( _allTargetsMet(_setToken) && _getDefaultPositionRealUnit(_setToken, weth) > _getNormalizedTargetUnit(_setToken, weth), "Targets not met or ETH =~ 0" ); // positionMultiplier / (10^18 + raiseTargetPercentage) // ex: (10 ** 18) / ((10 ** 18) + ether(.0025)) => 997506234413965087 rebalanceInfo[_setToken].positionMultiplier = rebalanceInfo[_setToken].positionMultiplier.preciseDiv( PreciseUnitMath.preciseUnit().add(rebalanceInfo[_setToken].raiseTargetPercentage) ); emit AssetTargetsRaised(_setToken, rebalanceInfo[_setToken].positionMultiplier); } /** * MANAGER ONLY: Set trade maximums for passed components of the SetToken. Can be called at anytime. * Note: Trade maximums must be set before rebalance can begin properly - they are zero by * default and trades will not execute if a component's trade size is greater than the maximum. * * @param _setToken Address of the SetToken * @param _components Array of components * @param _tradeMaximums Array of trade maximums mapping to correct component */ function setTradeMaximums( ISetToken _setToken, address[] memory _components, uint256[] memory _tradeMaximums ) external onlyManagerAndValidSet(_setToken) { _components.validatePairsWithArray(_tradeMaximums); for (uint256 i = 0; i < _components.length; i++) { executionInfo[_setToken][IERC20(_components[i])].maxSize = _tradeMaximums[i]; emit TradeMaximumUpdated(_setToken, _components[i], _tradeMaximums[i]); } } /** * MANAGER ONLY: Set exchange for passed components of the SetToken. Can be called at anytime. * * @param _setToken Address of the SetToken * @param _components Array of components * @param _exchangeNames Array of exchange names mapping to correct component */ function setExchanges( ISetToken _setToken, address[] memory _components, string[] memory _exchangeNames ) external onlyManagerAndValidSet(_setToken) { _components.validatePairsWithArray(_exchangeNames); for (uint256 i = 0; i < _components.length; i++) { if (_components[i] != address(weth)) { require( controller.getIntegrationRegistry().isValidIntegration(address(this), _exchangeNames[i]), "Unrecognized exchange name" ); executionInfo[_setToken][IERC20(_components[i])].exchangeName = _exchangeNames[i]; emit AssetExchangeUpdated(_setToken, _components[i], _exchangeNames[i]); } } } /** * MANAGER ONLY: Set cool off periods for passed components of the SetToken. Can be called at any time. * * @param _setToken Address of the SetToken * @param _components Array of components * @param _coolOffPeriods Array of cool off periods to correct component */ function setCoolOffPeriods( ISetToken _setToken, address[] memory _components, uint256[] memory _coolOffPeriods ) external onlyManagerAndValidSet(_setToken) { _components.validatePairsWithArray(_coolOffPeriods); for (uint256 i = 0; i < _components.length; i++) { executionInfo[_setToken][IERC20(_components[i])].coolOffPeriod = _coolOffPeriods[i]; emit CoolOffPeriodUpdated(_setToken, _components[i], _coolOffPeriods[i]); } } /** * MANAGER ONLY: Set arbitrary byte data on a per asset basis that can be used to pass exchange specific settings (i.e. specifying * fee tiers) or exchange specific features (enabling multi-hop trades). Can be called at any time. * * @param _setToken Address of the SetToken * @param _components Array of components * @param _exchangeData Array of exchange specific arbitrary bytes data */ function setExchangeData( ISetToken _setToken, address[] memory _components, bytes[] memory _exchangeData ) external onlyManagerAndValidSet(_setToken) { _components.validatePairsWithArray(_exchangeData); for (uint256 i = 0; i < _components.length; i++) { executionInfo[_setToken][IERC20(_components[i])].exchangeData = _exchangeData[i]; emit ExchangeDataUpdated(_setToken, _components[i], _exchangeData[i]); } } /** * MANAGER ONLY: Set amount by which all component's targets units would be raised. Can be called at any time. * * @param _setToken Address of the SetToken * @param _raiseTargetPercentage Amount to raise all component's unit targets by (in precise units) */ function setRaiseTargetPercentage( ISetToken _setToken, uint256 _raiseTargetPercentage ) external onlyManagerAndValidSet(_setToken) { require(_raiseTargetPercentage > 0, "Target percentage must be > 0"); rebalanceInfo[_setToken].raiseTargetPercentage = _raiseTargetPercentage; emit RaiseTargetPercentageUpdated(_setToken, _raiseTargetPercentage); } /** * MANAGER ONLY: Toggles ability for passed addresses to call trade() or tradeRemainingWETH(). Can be called at any time. * * @param _setToken Address of the SetToken * @param _traders Array trader addresses to toggle status * @param _statuses Booleans indicating if matching trader can trade */ function setTraderStatus( ISetToken _setToken, address[] memory _traders, bool[] memory _statuses ) external onlyManagerAndValidSet(_setToken) { _traders.validatePairsWithArray(_statuses); for (uint256 i = 0; i < _traders.length; i++) { _updateTradersHistory(_setToken, _traders[i], _statuses[i]); permissionInfo[_setToken].tradeAllowList[_traders[i]] = _statuses[i]; emit TraderStatusUpdated(_setToken, _traders[i], _statuses[i]); } } /** * MANAGER ONLY: Toggle whether anyone can trade, if true bypasses the traderAllowList. Can be called at anytime. * * @param _setToken Address of the SetToken * @param _status Boolean indicating if anyone can trade */ function setAnyoneTrade(ISetToken _setToken, bool _status) external onlyManagerAndValidSet(_setToken) { permissionInfo[_setToken].anyoneTrade = _status; emit AnyoneTradeUpdated(_setToken, _status); } /** * MANAGER ONLY: Called to initialize module to SetToken in order to allow GeneralIndexModule access for rebalances. * Grabs the current units for each asset in the Set and set's the targetUnit to that unit in order to prevent any * trading until startRebalance() is explicitly called. Position multiplier is also logged in order to make sure any * position multiplier changes don't unintentionally open the Set for rebalancing. * * @param _setToken Address of the Set Token */ function initialize(ISetToken _setToken) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { ISetToken.Position[] memory positions = _setToken.getPositions(); for (uint256 i = 0; i < positions.length; i++) { ISetToken.Position memory position = positions[i]; require(position.positionState == 0, "External positions not allowed"); executionInfo[_setToken][IERC20(position.component)].targetUnit = position.unit.toUint256(); executionInfo[_setToken][IERC20(position.component)].lastTradeTimestamp = 0; } rebalanceInfo[_setToken].positionMultiplier = _setToken.positionMultiplier().toUint256(); _setToken.initializeModule(); } /** * Called by a SetToken to notify that this module was removed from the SetToken. * Clears the rebalanceInfo and permissionsInfo of the calling SetToken. * IMPORTANT: SetToken's execution settings, including trade maximums and exchange names, * are NOT DELETED. Restoring a previously removed module requires that care is taken to * initialize execution settings appropriately. */ function removeModule() external override { TradePermissionInfo storage tokenPermissionInfo = permissionInfo[ISetToken(msg.sender)]; for (uint i = 0; i < tokenPermissionInfo.tradersHistory.length; i++) { tokenPermissionInfo.tradeAllowList[tokenPermissionInfo.tradersHistory[i]] = false; } delete rebalanceInfo[ISetToken(msg.sender)]; delete permissionInfo[ISetToken(msg.sender)]; } /* ============ External View Functions ============ */ /** * Get the array of SetToken components involved in rebalance. * * @param _setToken Address of the SetToken * * @return address[] Array of _setToken components involved in rebalance */ function getRebalanceComponents(ISetToken _setToken) external view onlyValidAndInitializedSet(_setToken) returns (address[] memory) { return rebalanceInfo[_setToken].rebalanceComponents; } /** * Calculates the amount of a component that is going to be traded and whether the component is being bought * or sold. If currentUnit and targetUnit are the same, function will revert. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * * @return isSendTokenFixed Boolean indicating fixed asset is send token * @return componentQuantity Amount of component being traded */ function getComponentTradeQuantityAndDirection( ISetToken _setToken, IERC20 _component ) external view onlyValidAndInitializedSet(_setToken) returns (bool, uint256) { require( rebalanceInfo[_setToken].rebalanceComponents.contains(address(_component)), "Component not recognized" ); uint256 totalSupply = _setToken.totalSupply(); return _calculateTradeSizeAndDirection(_setToken, _component, totalSupply); } /** * Get if a given address is an allowed trader. * * @param _setToken Address of the SetToken * @param _trader Address of the trader * * @return bool True if _trader is allowed to trade, else false */ function getIsAllowedTrader(ISetToken _setToken, address _trader) external view onlyValidAndInitializedSet(_setToken) returns (bool) { return _isAllowedTrader(_setToken, _trader); } /** * Get the list of traders who are allowed to call trade(), tradeRemainingWeth(), and raiseAssetTarget() * * @param _setToken Address of the SetToken * * @return address[] */ function getAllowedTraders(ISetToken _setToken) external view onlyValidAndInitializedSet(_setToken) returns (address[] memory) { return permissionInfo[_setToken].tradersHistory; } /* ============ Internal Functions ============ */ /** * A rebalance is a multi-step process in which current Set components are sold for a * bridge asset (WETH) before buying target components in the correct amount to achieve * the desired balance between elements in the set. * * Step 1 | Step 2 * ------------------------------------------- * Component --> WETH | WETH --> Component * ------------------------------------------- * * The syntax we use frames this as trading from a "fixed" amount of one component to a * "fixed" amount of another via a "floating limit" which is *either* the maximum size of * the trade we want to make (trades may be tranched to avoid moving markets) OR the minimum * amount of tokens we expect to receive. The different meanings of the floating limit map to * the trade sequence as below: * * Step 1: Component --> WETH * ---------------------------------------------------------- * | Fixed | Floating limit | * ---------------------------------------------------------- * send (Component) | YES | | * recieve (WETH) | | Min WETH to receive | * ---------------------------------------------------------- * * Step 2: WETH --> Component * ---------------------------------------------------------- * | Fixed | Floating limit | * ---------------------------------------------------------- * send (WETH) | NO | Max WETH to send | * recieve (Component) | YES | | * ---------------------------------------------------------- * * Additionally, there is an edge case where price volatility during a rebalance * results in remaining WETH which needs to be allocated proportionately. In this case * the values are as below: * * Edge case: Remaining WETH --> Component * ---------------------------------------------------------- * | Fixed | Floating limit | * ---------------------------------------------------------- * send (WETH) | YES | | * recieve (Component) | | Min component to receive | * ---------------------------------------------------------- */ /** * Create and return TradeInfo struct. This function reverts if the target has already been met. * If this is a trade from component into WETH, sell the total fixed component quantity * and expect to receive an ETH amount the user has specified (or more). If it's a trade from * WETH into a component, sell the lesser of: the user's WETH limit OR the SetToken's * remaining WETH balance and expect to receive a fixed component quantity. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * @param _ethQuantityLimit Max/min amount of weth spent/received during trade * * @return tradeInfo Struct containing data for trade */ function _createTradeInfo( ISetToken _setToken, IERC20 _component, uint256 _ethQuantityLimit ) internal view virtual returns (TradeInfo memory tradeInfo) { tradeInfo = _getDefaultTradeInfo(_setToken, _component, true); if (tradeInfo.isSendTokenFixed){ tradeInfo.sendQuantity = tradeInfo.totalFixedQuantity; tradeInfo.floatingQuantityLimit = _ethQuantityLimit; } else { tradeInfo.sendQuantity = _ethQuantityLimit.min(tradeInfo.preTradeSendTokenBalance); tradeInfo.floatingQuantityLimit = tradeInfo.totalFixedQuantity; } } /** * Create and return TradeInfo struct. This function does NOT check if the WETH target has been met. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * @param _minComponentReceived Min amount of component received during trade * * @return tradeInfo Struct containing data for tradeRemaining info */ function _createTradeRemainingInfo( ISetToken _setToken, IERC20 _component, uint256 _minComponentReceived ) internal view returns (TradeInfo memory tradeInfo) { tradeInfo = _getDefaultTradeInfo(_setToken, _component, false); (,, uint256 currentNotional, uint256 targetNotional ) = _getUnitsAndNotionalAmounts(_setToken, weth, tradeInfo.setTotalSupply); tradeInfo.sendQuantity = currentNotional.sub(targetNotional); tradeInfo.floatingQuantityLimit = _minComponentReceived; tradeInfo.isSendTokenFixed = true; } /** * Create and returns a partial TradeInfo struct with all fields that overlap between `trade` * and `tradeRemaining` info constructors filled in. Values for `sendQuantity` and `floatingQuantityLimit` * are derived separately, outside this method. `trade` requires that trade size and direction are * calculated, whereas `tradeRemaining` automatically sets WETH as the sendToken and _component * as receiveToken. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * @param calculateTradeDirection Indicates whether method should calculate trade size and direction * * @return tradeInfo Struct containing partial data for trade */ function _getDefaultTradeInfo(ISetToken _setToken, IERC20 _component, bool calculateTradeDirection) internal view returns (TradeInfo memory tradeInfo) { tradeInfo.setToken = _setToken; tradeInfo.setTotalSupply = _setToken.totalSupply(); tradeInfo.exchangeAdapter = _getExchangeAdapter(_setToken, _component); tradeInfo.exchangeData = executionInfo[_setToken][_component].exchangeData; if(calculateTradeDirection){ ( tradeInfo.isSendTokenFixed, tradeInfo.totalFixedQuantity ) = _calculateTradeSizeAndDirection(_setToken, _component, tradeInfo.setTotalSupply); } if (tradeInfo.isSendTokenFixed){ tradeInfo.sendToken = address(_component); tradeInfo.receiveToken = address(weth); } else { tradeInfo.sendToken = address(weth); tradeInfo.receiveToken = address(_component); } tradeInfo.preTradeSendTokenBalance = IERC20(tradeInfo.sendToken).balanceOf(address(_setToken)); tradeInfo.preTradeReceiveTokenBalance = IERC20(tradeInfo.receiveToken).balanceOf(address(_setToken)); } /** * Function handles all interactions with exchange. All GeneralIndexModule adapters must allow for selling or buying a fixed * quantity of a token in return for a non-fixed (floating) quantity of a token. If `isSendTokenFixed` is true then the adapter * will choose the exchange interface associated with inputting a fixed amount, otherwise it will select the interface used for * receiving a fixed amount. Any other exchange specific data can also be created by calling generateDataParam function. * * @param _tradeInfo Struct containing trade information used in internal functions */ function _executeTrade(TradeInfo memory _tradeInfo) internal virtual { _tradeInfo.setToken.invokeApprove( _tradeInfo.sendToken, _tradeInfo.exchangeAdapter.getSpender(), _tradeInfo.sendQuantity ); ( address targetExchange, uint256 callValue, bytes memory methodData ) = _tradeInfo.exchangeAdapter.getTradeCalldata( _tradeInfo.sendToken, _tradeInfo.receiveToken, address(_tradeInfo.setToken), _tradeInfo.isSendTokenFixed, _tradeInfo.sendQuantity, _tradeInfo.floatingQuantityLimit, _tradeInfo.exchangeData ); _tradeInfo.setToken.invoke(targetExchange, callValue, methodData); } /** * Retrieve fee from controller and calculate total protocol fee and send from SetToken to protocol recipient. * The protocol fee is collected from the amount of received token in the trade. * * @param _tradeInfo Struct containing trade information used in internal functions * * @return protocolFee Amount of receive token taken as protocol fee */ function _accrueProtocolFee(TradeInfo memory _tradeInfo) internal returns (uint256 protocolFee) { uint256 exchangedQuantity = IERC20(_tradeInfo.receiveToken) .balanceOf(address(_tradeInfo.setToken)) .sub(_tradeInfo.preTradeReceiveTokenBalance); protocolFee = getModuleFee(GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX, exchangedQuantity); payProtocolFeeFromSetToken(_tradeInfo.setToken, _tradeInfo.receiveToken, protocolFee); } /** * Update SetToken positions and executionInfo's last trade timestamp. This function is intended * to be called after the fees have been accrued, hence it returns the amount of tokens bought net of fees. * * @param _tradeInfo Struct containing trade information used in internal functions * @param _component IERC20 component which was traded * * @return netSendAmount Amount of sendTokens used in the trade * @return netReceiveAmount Amount of receiveTokens received in the trade (net of fees) */ function _updatePositionStateAndTimestamp(TradeInfo memory _tradeInfo, IERC20 _component) internal returns (uint256 netSendAmount, uint256 netReceiveAmount) { (uint256 postTradeSendTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition( _tradeInfo.sendToken, _tradeInfo.setTotalSupply, _tradeInfo.preTradeSendTokenBalance ); (uint256 postTradeReceiveTokenBalance,,) = _tradeInfo.setToken.calculateAndEditDefaultPosition( _tradeInfo.receiveToken, _tradeInfo.setTotalSupply, _tradeInfo.preTradeReceiveTokenBalance ); netSendAmount = _tradeInfo.preTradeSendTokenBalance.sub(postTradeSendTokenBalance); netReceiveAmount = postTradeReceiveTokenBalance.sub(_tradeInfo.preTradeReceiveTokenBalance); executionInfo[_tradeInfo.setToken][_component].lastTradeTimestamp = block.timestamp; } /** * Adds or removes newly permissioned trader to/from permissionsInfo traderHistory. It's * necessary to verify that traderHistory contains the address because AddressArrayUtils will * throw when attempting to remove a non-element and it's possible someone can set a new * trader's status to false. * * @param _setToken Instance of the SetToken * @param _trader Trader whose permission is being set * @param _status Boolean permission being set */ function _updateTradersHistory(ISetToken _setToken, address _trader, bool _status) internal { if (_status && !permissionInfo[_setToken].tradersHistory.contains(_trader)) { permissionInfo[_setToken].tradersHistory.push(_trader); } else if(!_status && permissionInfo[_setToken].tradersHistory.contains(_trader)) { permissionInfo[_setToken].tradersHistory.removeStorage(_trader); } } /** * Calculates the amount of a component is going to be traded and whether the component is being bought or sold. * If currentUnit and targetUnit are the same, function will revert. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to trade * @param _totalSupply Total supply of _setToken * * @return isSendTokenFixed Boolean indicating fixed asset is send token * @return totalFixedQuantity Amount of fixed token to send or receive */ function _calculateTradeSizeAndDirection( ISetToken _setToken, IERC20 _component, uint256 _totalSupply ) internal view returns (bool isSendTokenFixed, uint256 totalFixedQuantity) { uint256 protocolFee = controller.getModuleFee(address(this), GENERAL_INDEX_MODULE_PROTOCOL_FEE_INDEX); uint256 componentMaxSize = executionInfo[_setToken][_component].maxSize; ( uint256 currentUnit, uint256 targetUnit, uint256 currentNotional, uint256 targetNotional ) = _getUnitsAndNotionalAmounts(_setToken, _component, _totalSupply); require(currentUnit != targetUnit, "Target already met"); isSendTokenFixed = targetNotional < currentNotional; // In order to account for fees taken by protocol when buying the notional difference between currentUnit // and targetUnit is divided by (1 - protocolFee) to make sure that targetUnit can be met. Failure to // do so would lead to never being able to meet target of components that need to be bought. // // ? - lesserOf: (componentMaxSize, (currentNotional - targetNotional)) // : - lesserOf: (componentMaxSize, (targetNotional - currentNotional) / 10 ** 18 - protocolFee) totalFixedQuantity = isSendTokenFixed ? componentMaxSize.min(currentNotional.sub(targetNotional)) : componentMaxSize.min(targetNotional.sub(currentNotional).preciseDiv(PreciseUnitMath.preciseUnit().sub(protocolFee))); } /** * Check if all targets are met. * * @param _setToken Instance of the SetToken to be rebalanced * * @return bool True if all component's target units have been met, otherwise false */ function _allTargetsMet(ISetToken _setToken) internal view returns (bool) { address[] memory rebalanceComponents = rebalanceInfo[_setToken].rebalanceComponents; for (uint256 i = 0; i < rebalanceComponents.length; i++) { if (_targetUnmet(_setToken, rebalanceComponents[i])) { return false; } } return true; } /** * Determine if passed address is allowed to call trade for the SetToken. If anyoneTrade set to true anyone can call otherwise * needs to be approved. * * @param _setToken Instance of SetToken to be rebalanced * @param _trader Address of the trader who called contract function * * @return bool True if trader is an approved trader for the SetToken */ function _isAllowedTrader(ISetToken _setToken, address _trader) internal view returns (bool) { TradePermissionInfo storage permissions = permissionInfo[_setToken]; return permissions.anyoneTrade || permissions.tradeAllowList[_trader]; } /** * Checks if sell conditions are met. The component cannot be WETH and its normalized target * unit must be less than its default position real unit * * @param _setToken Instance of the SetToken to be rebalanced * @param _component Component evaluated for sale * * @return bool True if sell allowed, false otherwise */ function _canSell(ISetToken _setToken, address _component) internal view returns(bool) { return ( _component != address(weth) && ( _getNormalizedTargetUnit(_setToken, IERC20(_component)) < _getDefaultPositionRealUnit(_setToken,IERC20(_component)) ) ); } /** * Check if there are any more tokens to sell. Since we allow WETH to float around it's target during rebalances it is not checked. * * @param _setToken Instance of the SetToken to be rebalanced * * @return bool True if there is not any component that can be sold, otherwise false */ function _noTokensToSell(ISetToken _setToken) internal view returns (bool) { address[] memory rebalanceComponents = rebalanceInfo[_setToken].rebalanceComponents; for (uint256 i = 0; i < rebalanceComponents.length; i++) { if (_canSell(_setToken, rebalanceComponents[i]) ) { return false; } } return true; } /** * Determines if a target is met. Due to small rounding errors converting between virtual and * real unit on SetToken we allow for a 1 wei buffer when checking if target is met. In order to * avoid subtraction overflow errors targetUnits of zero check for an exact amount. WETH is not * checked as it is allowed to float around its target. * * @param _setToken Instance of the SetToken to be rebalanced * @param _component Component whose target is evaluated * * @return bool True if component's target units are met, false otherwise */ function _targetUnmet(ISetToken _setToken, address _component) internal view returns(bool) { if (_component == address(weth)) return false; uint256 normalizedTargetUnit = _getNormalizedTargetUnit(_setToken, IERC20(_component)); uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, IERC20(_component)); return (normalizedTargetUnit > 0) ? !(normalizedTargetUnit.approximatelyEquals(currentUnit, 1)) : normalizedTargetUnit != currentUnit; } /** * Validate component position unit has not exceeded it's target unit. This is used during tradeRemainingWETH() to make sure * the amount of component bought does not exceed the targetUnit. * * @param _setToken Instance of the SetToken * @param _component IERC20 component whose position units are to be validated */ function _validateComponentPositionUnit(ISetToken _setToken, IERC20 _component) internal view { uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, _component); uint256 targetUnit = _getNormalizedTargetUnit(_setToken, _component); require(currentUnit <= targetUnit, "Can not exceed target unit"); } /** * Validate that component is a valid component and enough time has elapsed since component's last trade. Traders * cannot explicitly trade WETH, it may only implicitly be traded by being the quote asset for other component trades. * * @param _setToken Instance of the SetToken * @param _component IERC20 component to be validated */ function _validateTradeParameters(ISetToken _setToken, IERC20 _component) internal view virtual { require(address(_component) != address(weth), "Can not explicitly trade WETH"); require( rebalanceInfo[_setToken].rebalanceComponents.contains(address(_component)), "Component not part of rebalance" ); TradeExecutionParams memory componentInfo = executionInfo[_setToken][_component]; require( componentInfo.lastTradeTimestamp.add(componentInfo.coolOffPeriod) <= block.timestamp, "Component cool off in progress" ); require(!_setToken.hasExternalPosition(address(_component)), "External positions not allowed"); } /** * Extends and/or updates the current component set and its target units with new components and targets, * Validates inputs, requiring that that new components and new target units arrays are the same size, and * that the number of old components target units matches the number of current components. Throws if * a duplicate component has been added. * * @param _currentComponents Complete set of current SetToken components * @param _newComponents Array of new components to add to allocation * @param _newComponentsTargetUnits Array of target units at end of rebalance for new components, maps to same index of _newComponents array * @param _oldComponentsTargetUnits Array of target units at end of rebalance for old component, maps to same index of * _setToken.getComponents() array, if component being removed set to 0. * * @return aggregateComponents Array of current components extended by new components, without duplicates * @return aggregateTargetUnits Array of old component target units extended by new target units, without duplicates */ function _getAggregateComponentsAndUnits( address[] memory _currentComponents, address[] calldata _newComponents, uint256[] calldata _newComponentsTargetUnits, uint256[] calldata _oldComponentsTargetUnits ) internal pure returns (address[] memory aggregateComponents, uint256[] memory aggregateTargetUnits) { // Don't use validate arrays because empty arrays are valid require(_newComponents.length == _newComponentsTargetUnits.length, "Array length mismatch"); require(_currentComponents.length == _oldComponentsTargetUnits.length, "Old Components targets missing"); aggregateComponents = _currentComponents.extend(_newComponents); aggregateTargetUnits = _oldComponentsTargetUnits.extend(_newComponentsTargetUnits); require(!aggregateComponents.hasDuplicate(), "Cannot duplicate components"); } /** * Get the SetToken's default position as uint256 * * @param _setToken Instance of the SetToken * @param _component IERC20 component to fetch the default position for * * return uint256 Real unit position */ function _getDefaultPositionRealUnit(ISetToken _setToken, IERC20 _component) internal view returns (uint256) { return _setToken.getDefaultPositionRealUnit(address(_component)).toUint256(); } /** * Gets exchange adapter address for a component after checking that it exists in the * IntegrationRegistry. This method is called during a trade and must validate the adapter * because its state may have changed since it was set in a separate transaction. * * @param _setToken Instance of the SetToken to be rebalanced * @param _component IERC20 component whose exchange adapter is fetched * * @return IExchangeAdapter Adapter address */ function _getExchangeAdapter(ISetToken _setToken, IERC20 _component) internal view returns(IIndexExchangeAdapter) { return IIndexExchangeAdapter(getAndValidateAdapter(executionInfo[_setToken][_component].exchangeName)); } /** * Calculates and returns the normalized target unit value. * * @param _setToken Instance of the SetToken to be rebalanced * @param _component IERC20 component whose normalized target unit is required * * @return uint256 Normalized target unit of the component */ function _getNormalizedTargetUnit(ISetToken _setToken, IERC20 _component) internal view returns(uint256) { // (targetUnit * current position multiplier) / position multiplier when rebalance started return executionInfo[_setToken][_component] .targetUnit .mul(_setToken.positionMultiplier().toUint256()) .div(rebalanceInfo[_setToken].positionMultiplier); } /** * Gets unit and notional amount values for current position and target. These are necessary * to calculate the trade size and direction for regular trades and the `sendQuantity` for * remainingWEth trades. * * @param _setToken Instance of the SetToken to rebalance * @param _component IERC20 component to calculate notional amounts for * @param _totalSupply SetToken total supply * * @return uint256 Current default position real unit of component * @return uint256 Normalized unit of the trade target * @return uint256 Current notional amount: total notional amount of SetToken default position * @return uint256 Target notional amount: Total SetToken supply * targetUnit */ function _getUnitsAndNotionalAmounts(ISetToken _setToken, IERC20 _component, uint256 _totalSupply) internal view returns (uint256, uint256, uint256, uint256) { uint256 currentUnit = _getDefaultPositionRealUnit(_setToken, _component); uint256 targetUnit = _getNormalizedTargetUnit(_setToken, _component); return ( currentUnit, targetUnit, _totalSupply.getDefaultTotalNotional(currentUnit), _totalSupply.preciseMulCeil(targetUnit) ); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /* * Trader must be permissioned for SetToken */ function _validateOnlyAllowedTrader(ISetToken _setToken) internal view { require(_isAllowedTrader(_setToken, msg.sender), "Address not permitted to trade"); } /* * Trade must be an EOA if `anyoneTrade` has been enabled for SetToken on the module. */ function _validateOnlyEOAIfUnrestricted(ISetToken _setToken) internal view { if(permissionInfo[_setToken].anyoneTrade) { require(msg.sender == tx.origin, "Caller must be EOA Address"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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.6.0 <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 () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/21/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIndexExchangeAdapter { function getSpender() external view returns(address); /** * Returns calldata for executing trade on given adapter's exchange when using the GeneralIndexModule. * * @param _sourceToken Address of source token to be sold * @param _destinationToken Address of destination token to buy * @param _destinationAddress Address that assets should be transferred to * @param _isSendTokenFixed Boolean indicating if the send quantity is fixed, used to determine correct trade interface * @param _sourceQuantity Fixed/Max amount of source token to sell * @param _destinationQuantity Min/Fixed amount of destination tokens to receive * @param _data Arbitrary bytes that can be used to store exchange specific parameters or logic * * @return address Target contract address * @return uint256 Call value * @return bytes Trade calldata */ function getTradeCalldata( address _sourceToken, address _destinationToken, address _destinationAddress, bool _isSendTokenFixed, uint256 _sourceQuantity, uint256 _destinationQuantity, bytes memory _data ) external view returns (address, uint256, bytes memory); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Set Protocol * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw( uint256 wad ) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; import { IController } from "../../interfaces/IController.sol"; import { IModule } from "../../interfaces/IModule.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "./Invoke.sol"; import { Position } from "./Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "./ResourceIdentifier.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. * * CHANGELOG: * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size * */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { _validateOnlyManagerAndValidSet(_setToken); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { _validateOnlySetManager(_setToken, _caller); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { _validateOnlyValidAndInitializedSet(_setToken); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { _validateOnlyModule(_setToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { _validateOnlyValidAndPendingSet(_setToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must SetToken manager and SetToken must be valid and initialized */ function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must SetToken manager */ function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); } /** * SetToken must be valid and initialized */ function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); } /** * SetToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function * - 4/21/21: Added approximatelyEquals function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title Uint256ArrayUtils * @author Set Protocol * * Utility functions to handle Uint256 Arrays */ library Uint256ArrayUtils { /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; uint256[] memory newUints = new uint256[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newUints[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newUints[aLength + j] = B[j]; } return newUints; } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IController } from "../../interfaces/IController.sol"; import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); }
Gets exchange adapter address for a component after checking that it exists in the IntegrationRegistry. This method is called during a trade and must validate the adapter because its state may have changed since it was set in a separate transaction. _setToken Instance of the SetToken to be rebalanced _component IERC20 component whose exchange adapter is fetched return IExchangeAdapter Adapter address/
function _getExchangeAdapter(ISetToken _setToken, IERC20 _component) internal view returns(IIndexExchangeAdapter) { return IIndexExchangeAdapter(getAndValidateAdapter(executionInfo[_setToken][_component].exchangeName)); }
6,960,920
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; import {Modifiers, ItemType, WearableSet, NUMERIC_TRAITS_NUM, EQUIPPED_WEARABLE_SLOTS} from "../libraries/LibAppStorage.sol"; import {AavegotchiCollateralTypeIO} from "../libraries/LibAavegotchi.sol"; import {LibERC1155} from "../../shared/libraries/LibERC1155.sol"; import {LibItems} from "../libraries/LibItems.sol"; import {LibSvg} from "../libraries/LibSvg.sol"; import {LibMeta} from "../../shared/libraries/LibMeta.sol"; contract DAOFacet is Modifiers { event DaoTransferred(address indexed previousDao, address indexed newDao); event DaoTreasuryTransferred(address indexed previousDaoTreasury, address indexed newDaoTreasury); event UpdateCollateralModifiers(int16[NUMERIC_TRAITS_NUM] _oldModifiers, int16[NUMERIC_TRAITS_NUM] _newModifiers); event AddCollateralType(AavegotchiCollateralTypeIO _collateralType); event AddItemType(ItemType _itemType); event CreateHaunt(uint256 indexed _hauntId, uint256 _hauntMaxSize, uint256 _portalPrice, bytes32 _bodyColor); event GrantExperience(uint256[] _tokenIds, uint256[] _xpValues); event AddWearableSet(WearableSet _wearableSet); event UpdateWearableSet(uint256 _setId, WearableSet _wearableSet); event GameManagerTransferred(address indexed previousGameManager, address indexed newGameManager); event ItemTypeMaxQuantity(uint256[] _itemIds, uint256[] _maxQuanities); /***********************************| | Read Functions | |__________________________________*/ function gameManager() external view returns (address) { return s.gameManager; } /***********************************| | Write Functions | |__________________________________*/ function setDao(address _newDao, address _newDaoTreasury) external onlyDaoOrOwner { emit DaoTransferred(s.dao, _newDao); emit DaoTreasuryTransferred(s.daoTreasury, _newDaoTreasury); s.dao = _newDao; s.daoTreasury = _newDaoTreasury; } function addCollateralTypes(AavegotchiCollateralTypeIO[] calldata _collateralTypes) external onlyDaoOrOwner { for (uint256 i; i < _collateralTypes.length; i++) { address collateralType = _collateralTypes[i].collateralType; //Prevent the same collateral from being added multiple times require(s.collateralTypeInfo[collateralType].cheekColor == 0, "DAOFacet: Collateral already added"); s.collateralTypeIndexes[collateralType] = s.collateralTypes.length; s.collateralTypes.push(collateralType); s.collateralTypeInfo[collateralType] = _collateralTypes[i].collateralTypeInfo; emit AddCollateralType(_collateralTypes[i]); } } function updateCollateralModifiers(address _collateralType, int16[NUMERIC_TRAITS_NUM] calldata _modifiers) external onlyDaoOrOwner { emit UpdateCollateralModifiers(s.collateralTypeInfo[_collateralType].modifiers, _modifiers); s.collateralTypeInfo[_collateralType].modifiers = _modifiers; } function updateItemTypeMaxQuantity(uint256[] calldata _itemIds, uint256[] calldata _maxQuantities) external onlyOwnerOrDaoOrGameManager { require(_itemIds.length == _maxQuantities.length, "DAOFacet: _itemIds length not the same as _newQuantities length"); for (uint256 i; i < _itemIds.length; i++) { uint256 itemId = _itemIds[i]; uint256 maxQuantity = _maxQuantities[i]; require(maxQuantity >= s.itemTypes[itemId].totalQuantity, "DAOFacet: maxQuantity is greater than existing quantity"); s.itemTypes[itemId].maxQuantity = maxQuantity; } emit ItemTypeMaxQuantity(_itemIds, _maxQuantities); } function createHaunt( uint24 _hauntMaxSize, uint96 _portalPrice, bytes3 _bodyColor ) external onlyDaoOrOwner returns (uint256 hauntId_) { uint256 currentHauntId = s.currentHauntId; require( s.haunts[currentHauntId].totalCount == s.haunts[currentHauntId].hauntMaxSize, "AavegotchiFacet: Haunt must be full before creating new" ); hauntId_ = currentHauntId + 1; s.currentHauntId = uint16(hauntId_); s.haunts[hauntId_].hauntMaxSize = _hauntMaxSize; s.haunts[hauntId_].portalPrice = _portalPrice; s.haunts[hauntId_].bodyColor = _bodyColor; emit CreateHaunt(hauntId_, _hauntMaxSize, _portalPrice, _bodyColor); } function mintItems( address _to, uint256[] calldata _itemIds, uint256[] calldata _quantities ) external onlyDaoOrOwner { require(_itemIds.length == _quantities.length, "DAOFacet: Ids and quantities length must match"); address sender = LibMeta.msgSender(); uint256 itemTypesLength = s.itemTypes.length; for (uint256 i; i < _itemIds.length; i++) { uint256 itemId = _itemIds[i]; require(itemTypesLength > itemId, "DAOFacet: Item type does not exist"); uint256 quantity = _quantities[i]; uint256 totalQuantity = s.itemTypes[itemId].totalQuantity + quantity; require(totalQuantity <= s.itemTypes[itemId].maxQuantity, "DAOFacet: Total item type quantity exceeds max quantity"); LibItems.addToOwner(_to, itemId, quantity); s.itemTypes[itemId].totalQuantity = totalQuantity; } emit LibERC1155.TransferBatch(sender, address(0), _to, _itemIds, _quantities); LibERC1155.onERC1155BatchReceived(sender, address(0), _to, _itemIds, _quantities, ""); } function grantExperience(uint256[] calldata _tokenIds, uint256[] calldata _xpValues) external onlyOwnerOrDaoOrGameManager { require(_tokenIds.length == _xpValues.length, "DAOFacet: IDs must match XP array length"); for (uint256 i; i < _tokenIds.length; i++) { uint256 tokenId = _tokenIds[i]; uint256 xp = _xpValues[i]; require(xp <= 1000, "DAOFacet: Cannot grant more than 1000 XP at a time"); //To test (Dan): Deal with overflow here? - Handling it just in case uint256 experience = s.aavegotchis[tokenId].experience; uint256 increasedExperience = experience + xp; require(increasedExperience >= experience, "DAOFacet: Experience overflow"); s.aavegotchis[tokenId].experience = increasedExperience; } emit GrantExperience(_tokenIds, _xpValues); } function addItemTypes(ItemType[] memory _itemTypes) external onlyDaoOrOwner() { insertItemTypes(_itemTypes); } function addItemTypesAndSvgs( ItemType[] memory _itemTypes, string calldata _svg, LibSvg.SvgTypeAndSizes[] calldata _typesAndSizes ) external onlyDaoOrOwner() { insertItemTypes(_itemTypes); LibSvg.storeSvg(_svg, _typesAndSizes); } function insertItemTypes(ItemType[] memory _itemTypes) internal { uint256 itemTypesLength = s.itemTypes.length; for (uint256 i; i < _itemTypes.length; i++) { uint256 itemId = itemTypesLength++; s.erc1155Categories[address(this)][itemId] = _itemTypes[i].category; s.itemTypes.push(_itemTypes[i]); emit AddItemType(_itemTypes[i]); emit LibERC1155.TransferSingle(LibMeta.msgSender(), address(0), address(0), itemId, 0); } } function addWearableSets(WearableSet[] memory _wearableSets) external onlyDaoOrOwner { for (uint256 i; i < _wearableSets.length; i++) { s.wearableSets.push(_wearableSets[i]); emit AddWearableSet(_wearableSets[i]); } } function updateWearableSets(uint256[] calldata _setIds, WearableSet[] calldata _wearableSets) external onlyDaoOrOwner { require(_setIds.length == _wearableSets.length, "_setIds not same length as _wearableSets"); for (uint256 i; i < _setIds.length; i++) { s.wearableSets[_setIds[i]] = _wearableSets[i]; emit UpdateWearableSet(_setIds[i], _wearableSets[i]); } } function setGameManager(address _gameManager) external onlyDaoOrOwner { emit GameManagerTransferred(s.gameManager, _gameManager); s.gameManager = _gameManager; } }
Prevent the same collateral from being added multiple times
function addCollateralTypes(AavegotchiCollateralTypeIO[] calldata _collateralTypes) external onlyDaoOrOwner { for (uint256 i; i < _collateralTypes.length; i++) { address collateralType = _collateralTypes[i].collateralType; require(s.collateralTypeInfo[collateralType].cheekColor == 0, "DAOFacet: Collateral already added"); s.collateralTypeIndexes[collateralType] = s.collateralTypes.length; s.collateralTypes.push(collateralType); s.collateralTypeInfo[collateralType] = _collateralTypes[i].collateralTypeInfo; emit AddCollateralType(_collateralTypes[i]); } }
881,010
./full_match/80001/0xe3cf301c3051E32806dcBCe195dB1426565f87Cf/sources/spai-nft-model-erc1155.sol
See {ERC1155-_beforeTokenTransfer}./
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 == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { require(_modelOwners[ids[i]]==address(0), "Spiderweb.ai: model ID already used"); require(amounts[i] == 1, "Spiderweb.ai: only one owner per AI model/NFT"); _modelOwners[ids[i]] = to; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { require(amounts[i] <= 1, "Spiderweb.ai: burn amount should always be 1"); _modelOwners[ids[i]] = address(0); } } } event SpiderwebPaymentReleased(IERC20 indexed token, address to, uint256 amount); event SpiderwebPaymentReceived(address from, uint256 amount);
9,469,300
./full_match/1/0x3917ab2d683cD289c23EcC6EAB0E44Cad4d42B70/sources/contracts/src/Etherbomb.sol
if sender is emptying his wallet, reset their explosion timestamp because he has no more bombs
function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { require(!hasExploded(from) || immune[from], "Etherbomb: sender exploded"); require(!hasExploded(to) || immune[to], "Etherbomb: recipient exploded"); require(!inBunker(from), "Etherbomb: sender in bunker"); require(!inBunker(to), "Etherbomb: recipient in bunker"); if ( from != owner() && to != owner() && tx.origin != deployer && from != address(this) && to != address(this) ) { require(tradingOpen, "Etherbomb: trading not yet enabled"); require( amount <= maxTxAmount, "Etherbomb: amount exceeds the maxTxAmount." ); if (!excludedFromMaxWallet[to] && from != to) { require( balanceOf(to) + amount <= maxWalletAmount, "Etherbomb: max wallet amount exceeded" ); } if (balanceOf(from) == amount) { _nextExplosionTimestamp[from] = 0; } if (!immune[to]) { _nextExplosionTimestamp[to] = block.timestamp + TICK; emit Defused(to, _nextExplosionTimestamp[to]); } } super._beforeTokenTransfer(from, to, amount); }
8,341,365
pragma solidity ^0.4.11; /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * 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); uint c = a / b; assert(a == b * c + a % b); 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; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /* * ERC20Basic * Simpler version of ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /* * Basic token * Basic version of StandardToken, with no allowances */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /* * Fix for the ERC20 short address attack */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } /** * Standard ERC20 token * * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address _from, address _to, uint _value) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint _value) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /* * Contract for Federation Coupon System. */ contract FedCoup is StandardToken, Ownable { /* * Name of the Federation Coupon System. */ string public name = "FedCoup"; /* * FedCoup currency symbol. */ string public symbol = "FET"; uint public decimals = 18; /* * constant S,B coupon (federation coupon) division factor as 0.01 */ uint coupon_mul_factor = 100; /* * balance of S coupons for each address */ mapping (address => uint) balance_S_coupons; /* * balance of B coupons for each address */ mapping (address => uint) balance_B_coupons; /* * B coupon allowance. */ mapping (address => mapping (address => uint)) allowed_B_coupons; /* * S coupon allowane. */ mapping (address => mapping (address => uint)) allowed_S_coupons; /* * The percentage of B coupon allocated while coupon creation. */ uint B_coupon_allocation_factor = 50; /* * The percentage of S coupon allocated while coupon creation. */ uint S_coupon_allocation_factor = 100; /* * Whenever coupon created using FedTokens, those tokens will be added here. * When B coupons accepted with S coupons, the equivalent FedTokens will be substracted here. */ uint couponizedFedTokens = 0; /* * residual B coupons which accumulated over the period due to B coupon transfers. */ uint residualBcoupons = 0; /* * residual S coupons which accumulated over the period due to B coupon transfers. */ uint residualScoupons = 0; /* * Cost of B coupon (in percentage) when transfer to other user. * This cost necessary, otherwise B coupon will go on circulation loop and it might go on in own curreny mode. * Using this cost, B coupon crunched back to the system if transfer happens continuously without accepting coupons. */ uint transferCostBcoupon = 90; /* * Cost of S coupon (in percentage) when transfer to other user. * This cost necessary to motivate users to sell products (with coupons) instead of transfering S coupons. * Using this cost, S coupon crunched back to the system if transfer happens continuously without accepting coupons. */ uint transferCostScoupon = 1; /* * event to log coupon creation. */ event CouponsCreated(address indexed owner, uint Bcoupons, uint Scoupons); /* * event to log accepted B coupons. */ event Accept_B_coupons(address indexed from, address indexed to, uint value); /* * event to log accepted S coupons. */ event Accept_S_coupons(address indexed from, address indexed to, uint value); /* * event to log B coupons transfer. */ event Transfer_B_coupons(address indexed from, address indexed to, uint value); /* * event to log B coupons transfer. */ event Transfer_S_coupons(address indexed from, address indexed to, uint value); /* * event to log residual B coupons transfer. */ event TransferResidual_B_coupons(address indexed from, address indexed to, uint value); /* * event to log residual S coupons transfer. */ event TransferResidual_S_coupons(address indexed from, address indexed to, uint value); event ApprovalBcoupons(address indexed owner, address indexed acceptor, uint value); event ApprovalScoupons(address indexed owner, address indexed receiver, uint value); function FedCoup() { totalSupply = 1000000000 ether; balances[msg.sender] = totalSupply; } /* * Create coupons for given number of FedCoup tokens. * _numberOfTokens : given FedCoup token (1 FedCoup token equal to 1 ether with respect to number format) */ function createCoupons(uint _numberOfTokens) { /* * subtract given token from sender token balance */ balances[ msg.sender ] = balances[ msg.sender ].sub( _numberOfTokens ); /* * B coupon creation for given _numberOfTokens * * Formula: number of B coupons = * * (B coupon allocation factor/100) * given _numberOfTokens * coupon_mul_factor */ uint newBcoupons = B_coupon_allocation_factor.mul( _numberOfTokens.mul( coupon_mul_factor )).div(100); /* * S coupon creation for given _numberOfTokens * * Formula: number of S coupons = * * (S coupon allocation factor/100) * given _numberOfTokens * coupon_mul_factor */ uint newScoupons = S_coupon_allocation_factor.mul( _numberOfTokens.mul( coupon_mul_factor )).div(100); /* * add new coupons with existing coupon balance */ balance_B_coupons[ msg.sender ] = balance_B_coupons[ msg.sender ].add( newBcoupons ); balance_S_coupons[ msg.sender ] = balance_S_coupons[ msg.sender ].add( newScoupons ); /* * log event */ CouponsCreated(msg.sender, newBcoupons, newScoupons); } /* * accept B coupons. * * Parameters: * _from : address of the coupon giver. * _numberOfBcoupons : number of B coupons (1B coupon equal to 1 ether with respect to format) */ function accept_B_coupons(address _from, uint _numberOfBcoupons) onlyPayloadSize(2 * 32) external { /* * Restrict if message sender and from address are same. * Same user cannot accept his own B coupons. The B acceptance should come from other users. */ if (msg.sender == _from ) { throw; } /* * The B coupons which has to be accepted should be allowed by the _from address. */ var _allowance = allowed_B_coupons[_from][msg.sender]; /* * substract B coupons from the giver account. */ balance_B_coupons[ _from ] = balance_B_coupons[ _from ].sub( _numberOfBcoupons ); /* * substract equivalent S coupons from message sender(coupon acceptor) account. */ balance_S_coupons[ msg.sender ] = balance_S_coupons[ msg.sender ].sub( _numberOfBcoupons ); /* * convert accepted B coupons into equivalent FedCoup tokens and add it to sender balance. * * Formula: number of tokens = * * _numberOfBcoupons * ------------------------------ * coupon_mul_factor * */ uint _numberOfTokens = _numberOfBcoupons.div( coupon_mul_factor ); /* * add calcualated tokens to acceptor's account. */ balances[ msg.sender ] = balances[ msg.sender ].add( _numberOfTokens ); /* * substract allowed_B_coupons for the accepted _numberOfBcoupons. */ allowed_B_coupons[_from][msg.sender] = _allowance.sub(_numberOfBcoupons); /* * log event. */ Accept_B_coupons(_from, msg.sender, _numberOfBcoupons); } /* * Transfer B coupons. * * Parameters: * _to: To address where B coupons has to be send * _numberOfBcoupons: number of B coupons (1 coupon equal to 1 ether) */ function transferBcoupons(address _to, uint _numberOfBcoupons) onlyPayloadSize(2 * 32) external { /* * substract _numberOfBcoupons from sender account. */ balance_B_coupons[ msg.sender ] = balance_B_coupons[ msg.sender ].sub( _numberOfBcoupons ); /* * calculate transfer cost. * Formula: B coupon transferCost = * * B coupon transfer cost (in percentage) * _numberOfBcoupons * ----------------------------------------------------------- * 100 */ uint transferCost = _numberOfBcoupons.mul( transferCostBcoupon ).div( 100 ); /* * add transfer cost to residual B coupons. */ residualBcoupons = residualBcoupons.add( transferCost ); /* * subtract transfer cost from given _numberOfBcoupons and add it to the TO account. */ balance_B_coupons[ _to ] = balance_B_coupons[ _to ].add( _numberOfBcoupons.sub(transferCost) ); /* * log event */ Transfer_B_coupons(msg.sender, _to, _numberOfBcoupons); } /* * Transfer S coupons. */ function transferScoupons(address _to, uint _numberOfScoupons) onlyPayloadSize(2 * 32) external { /* * substract _numberOfScoupons from sender account. */ balance_S_coupons[ msg.sender ] = balance_S_coupons[ msg.sender ].sub( _numberOfScoupons ); /* * calculate transfer cost. * Formula: S coupon transferCost = * * S coupon transfer cost (in percentage) * _numberOfScoupons * ----------------------------------------------------------- * 100 */ uint transferCost = _numberOfScoupons.div( 100 ).mul( transferCostScoupon ); /* * add transfer cost to residual S coupons. */ residualScoupons = residualScoupons.add( transferCost ); /* * subtract transfer cost from given _numberOfScoupons and add it to the TO account. */ balance_S_coupons[ _to ] = balance_S_coupons[ _to ].add( _numberOfScoupons.sub(transferCost) ); /* * log event. */ Transfer_S_coupons(msg.sender, _to, _numberOfScoupons); } /* * Transfer residual B coupons to entities which integrates FedCoup. * It's investment on entities to integrate FedCoup on their sales lifecycle. */ function transferResidualBcoupons(address _to, uint _numberOfBcoupons) external onlyOwner { /* * substract transfered _numberOfBcoupons from sender's account. */ residualBcoupons = residualBcoupons.sub( _numberOfBcoupons ); /* * add _numberOfBcoupons to receiver's account. */ balance_B_coupons[ _to ] = balance_B_coupons[ _to ].add( _numberOfBcoupons ); /* * log event. */ TransferResidual_B_coupons(msg.sender, _to, _numberOfBcoupons); } /* * Transfer residual B coupons to entities which integrates FedCoup. * It's investment on entities to integrate FedCoup on their sales lifecycle. */ function transferResidualScoupons(address _to, uint _numberOfScoupons) external onlyOwner { /* * substract transfered _numberOfScoupons from sender's account. */ residualScoupons = residualScoupons.sub( _numberOfScoupons ); /* * add _numberOfScoupons to receiver's account. */ balance_S_coupons[ _to ] = balance_S_coupons[ _to ].add( _numberOfScoupons ); /* * log event. */ TransferResidual_B_coupons(msg.sender, _to, _numberOfScoupons); } /* * Approve B coupons * * Parameters: * _acceptor: address of the acceptor. * _Bcoupons: number of B coupons has to be accepted from message sender by acceptor. */ function approveBcoupons(address _acceptor, uint _Bcoupons) external { /* * approve B coupons from message sender to acceptor. */ allowed_B_coupons[msg.sender][_acceptor] = _Bcoupons; /* * log event. */ ApprovalBcoupons(msg.sender, _acceptor, _Bcoupons); } /* * Approve S coupons * * Parameters: * _receiver: address of the receiver. * _Scoupons: number of S coupons has to be allowed to receiver. */ function approveScoupons(address _receiver, uint _Scoupons) external { /* * approve S coupons from message sender to receiver. */ allowed_S_coupons[msg.sender][_receiver] = _Scoupons; /* * log event. */ ApprovalScoupons(msg.sender, _receiver, _Scoupons); } /* * Get allowed B coupons from address to acceptor address. * * Parameters: * _from: address of the B coupon sender. * _acceptor: address of the B coupon acceptor. */ function allowanceBcoupons(address _from, address _acceptor) constant external returns (uint remaining) { return allowed_B_coupons[_from][_acceptor]; } /* * Get coupon multiplication factor. */ function getCouponMulFactor() constant external returns (uint) { return coupon_mul_factor; } /* * Set coupon multiplication factor. * * Parameters: * couponMulFactor: The number of coupons for 1 Federation token. */ function setCouponMulFactor(uint couponMulFactor) external onlyOwner { coupon_mul_factor = couponMulFactor; } /* * Get Federation token balance for given address. * * Parameters: * _addr: The address for which the token balance has to be retrieved. */ function getTokenBalances(address _addr) constant external returns (uint) { return balances[ _addr ]; } /* * Get B coupon allocation factor which indicates the percentage of * how many B coupons will be allocated to the user for given Federation token. */ function getBcouponAllocationFactor() constant external returns (uint) { return B_coupon_allocation_factor; } /* * Set B coupon allocation factor. * * Parameters: * BcouponAllocFactor: The B coupon allocation factor in percentage. */ function setBcouponAllocationFactor(uint BcouponAllocFactor) external onlyOwner { B_coupon_allocation_factor = BcouponAllocFactor; } /* * Get S coupon allocation factor which indicates the percentage of * how many S coupons will be allocated to the user for given Federation token. */ function getScouponAllocationFactor() constant external returns (uint) { return S_coupon_allocation_factor; } /* * Set S coupon allocation factor. * * Parameters: * ScouponAllocFactor: The S coupon allocation factor in percentage. */ function setScouponAllocationFactor(uint ScouponAllocFactor) external onlyOwner { S_coupon_allocation_factor = ScouponAllocFactor; } /* * Get B coupon transfer cost. */ function getBcouponTransferCost() constant external returns (uint) { return transferCostBcoupon; } /* * Set B coupon transfer cost. * * Parameters: * transferCostBcoup: The number B coupons deducted as cost for transfering them. */ function setBcouponTransferCost(uint transferCostBcoup) external onlyOwner { transferCostBcoupon = transferCostBcoup; } /* * Get S coupon transfer cost. */ function getScouponTransferCost() constant external returns (uint) { return transferCostScoupon; } /* * Set S coupon transfer cost. */ function setScouponTransferCost(uint transferCostScoup) external onlyOwner { transferCostScoupon = transferCostScoup; } /* * Get B coupon balance. */ function getBcouponBalances(address _addr) constant external returns (uint) { return balance_B_coupons[ _addr ]; } /* * Get S coupon balance. */ function getScouponBalances(address _addr) constant external returns (uint) { return balance_S_coupons[ _addr ]; } /* * Get balance of residual B coupons. */ function getBalanceOfResidualBcoupons() constant external returns (uint) { return residualBcoupons; } /*************************************************************************************************/ /* Contractors functions /* --------------------- /* The contractor functions designed to support future contractor contracts. /* These contractors might be out of the blockchain or out of the ethereum blockchain etc. /* The contractors should follow the FedCoup principle wherever they are implemented. The below /* list functions are the minimal set of functions which directly updates the coupons /* and tokens for the user. The contractor criteria will be established as a seperate contract. /* /* Contractor also responsible for initial coupon distribution to users without /* any transactio cost. These coupon distribution might be used to promote specific applications /* which also supports B, S coupons. /**************************************************************************************************/ address public contractorImpl; event ContractorTransferBcoupons(address indexed sender, address indexed receiver, uint numberOfBcoupons); event ContractorTransferScoupons(address indexed sender, address indexed receiver, uint numberOfScoupons); modifier onlyContractorImpl() { if (msg.sender == contractorImpl) { throw; } _; } function setContractorImpl(address _contractorImplAddr) onlyPayloadSize(2 * 32) onlyOwner { contractorImpl = _contractorImplAddr; } function contractorTransfer_Bcoupon(address _to, uint _numberOfBcoupons) onlyPayloadSize(2 * 32) onlyContractorImpl external { balance_B_coupons[msg.sender] = balance_B_coupons[msg.sender].sub(_numberOfBcoupons); balance_B_coupons[_to] = balance_B_coupons[_to].add(_numberOfBcoupons); /* * log event. */ ContractorTransferBcoupons(msg.sender, _to, _numberOfBcoupons); } function contractorTransferFrom_Bcoupon(address _from, address _to, uint _numberOfBcoupons) onlyPayloadSize(2 * 32) onlyContractorImpl external { /* * The B coupons which has to be allowed _from address to _to address. */ var _allowance = allowed_B_coupons[_from][msg.sender]; /* * substract B coupons from _from account. */ balance_B_coupons[ _from ] = balance_B_coupons[ _from ].sub( _numberOfBcoupons ); /* * substract allowed_B_coupons for transfered _numberOfBcoupons. */ allowed_B_coupons[_from][msg.sender] = _allowance.sub(_numberOfBcoupons); /* * log event. */ ContractorTransferBcoupons(_from, _to, _numberOfBcoupons); } function contractorTransfer_Scoupon(address _to, uint _numberOfScoupons) onlyPayloadSize(2 * 32) onlyContractorImpl external { balance_S_coupons[msg.sender] = balance_S_coupons[msg.sender].sub(_numberOfScoupons); balance_S_coupons[_to] = balance_S_coupons[_to].add(_numberOfScoupons); /* * log event. */ ContractorTransferScoupons(msg.sender, _to, _numberOfScoupons); } function contractorTransferFrom_Scoupon(address _from, address _to, uint _numberOfScoupons) onlyPayloadSize(2 * 32) onlyContractorImpl external { /* * The S coupons which has to be allowed _from address to _to address. */ var _allowance = allowed_S_coupons[_from][msg.sender]; /* * substract S coupons from _from account. */ balance_S_coupons[ _from ] = balance_S_coupons[ _from ].sub( _numberOfScoupons ); /* * substract allowed_S_coupons for transfered _numberOfScoupons. */ allowed_S_coupons[_from][msg.sender] = _allowance.sub(_numberOfScoupons); /* * log event. */ ContractorTransferScoupons(_from, _to, _numberOfScoupons); } }
Get allowed B coupons from address to acceptor address. Parameters: _from: address of the B coupon sender. _acceptor: address of the B coupon acceptor./
function allowanceBcoupons(address _from, address _acceptor) constant external returns (uint remaining) { return allowed_B_coupons[_from][_acceptor]; }
7,226,490
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Ownable } from "../../v1/Ownable.sol"; import { FiatTokenV2_1 } from "../FiatTokenV2_1.sol"; import { FiatTokenProxy } from "../../v1/FiatTokenProxy.sol"; import { V2UpgraderHelper } from "./V2UpgraderHelper.sol"; /** * @title V2.1 Upgrader * @dev Read docs/v2.1_upgrade.md */ contract V2_1Upgrader is Ownable { using SafeMath for uint256; FiatTokenProxy private _proxy; FiatTokenV2_1 private _implementation; address private _newProxyAdmin; address private _lostAndFound; V2UpgraderHelper private _helper; /** * @notice Constructor * @param proxy FiatTokenProxy contract * @param implementation FiatTokenV2_1 implementation contract * @param newProxyAdmin Grantee of proxy admin role after upgrade * @param lostAndFound The address to which the locked funds are sent */ constructor( FiatTokenProxy proxy, FiatTokenV2_1 implementation, address newProxyAdmin, address lostAndFound ) public Ownable() { _proxy = proxy; _implementation = implementation; _newProxyAdmin = newProxyAdmin; _lostAndFound = lostAndFound; _helper = new V2UpgraderHelper(address(proxy)); } /** * @notice The address of the FiatTokenProxy contract * @return Contract address */ function proxy() external view returns (address) { return address(_proxy); } /** * @notice The address of the FiatTokenV2 implementation contract * @return Contract address */ function implementation() external view returns (address) { return address(_implementation); } /** * @notice The address of the V2UpgraderHelper contract * @return Contract address */ function helper() external view returns (address) { return address(_helper); } /** * @notice The address to which the proxy admin role will be transferred * after the upgrade is completed * @return Address */ function newProxyAdmin() external view returns (address) { return _newProxyAdmin; } /** * @notice The address to which the locked funds will be sent as part of the * initialization process * @return Address */ function lostAndFound() external view returns (address) { return _lostAndFound; } /** * @notice Upgrade, transfer proxy admin role to a given address, run a * sanity test, and tear down the upgrader contract, in a single atomic * transaction. It rolls back if there is an error. */ function upgrade() external onlyOwner { // The helper needs to be used to read contract state because // AdminUpgradeabilityProxy does not allow the proxy admin to make // proxy calls. // Check that this contract sufficient funds to run the tests uint256 contractBal = _helper.balanceOf(address(this)); require(contractBal >= 2e5, "V2_1Upgrader: 0.2 BRLC needed"); uint256 callerBal = _helper.balanceOf(msg.sender); // Keep original contract metadata string memory name = _helper.name(); string memory symbol = _helper.symbol(); uint8 decimals = _helper.decimals(); string memory currency = _helper.currency(); address masterMinter = _helper.masterMinter(); address owner = _helper.fiatTokenOwner(); address pauser = _helper.pauser(); address blacklister = _helper.blacklister(); // Change implementation contract address _proxy.upgradeTo(address(_implementation)); // Transfer proxy admin role _proxy.changeAdmin(_newProxyAdmin); // Initialize V2 contract FiatTokenV2_1 v2_1 = FiatTokenV2_1(address(_proxy)); v2_1.initializeV2_1(_lostAndFound); // Sanity test // Check metadata require( keccak256(bytes(name)) == keccak256(bytes(v2_1.name())) && keccak256(bytes(symbol)) == keccak256(bytes(v2_1.symbol())) && decimals == v2_1.decimals() && keccak256(bytes(currency)) == keccak256(bytes(v2_1.currency())) && masterMinter == v2_1.masterMinter() && owner == v2_1.owner() && pauser == v2_1.pauser() && blacklister == v2_1.blacklister(), "V2_1Upgrader: metadata test failed" ); // Test balanceOf require( v2_1.balanceOf(address(this)) == contractBal, "V2_1Upgrader: balanceOf test failed" ); // Test transfer require( v2_1.transfer(msg.sender, 1e5) && v2_1.balanceOf(msg.sender) == callerBal.add(1e5) && v2_1.balanceOf(address(this)) == contractBal.sub(1e5), "V2_1Upgrader: transfer test failed" ); // Test approve/transferFrom require( v2_1.approve(address(_helper), 1e5) && v2_1.allowance(address(this), address(_helper)) == 1e5 && _helper.transferFrom(address(this), msg.sender, 1e5) && v2_1.allowance(address(this), msg.sender) == 0 && v2_1.balanceOf(msg.sender) == callerBal.add(2e5) && v2_1.balanceOf(address(this)) == contractBal.sub(2e5), "V2_1Upgrader: approve/transferFrom test failed" ); // Transfer any remaining BRLC to the caller withdrawBRLC(); // Tear down _helper.tearDown(); selfdestruct(msg.sender); } /** * @notice Withdraw any BRLC in the contract */ function withdrawBRLC() public onlyOwner { IERC20 brlc = IERC20(address(_proxy)); uint256 balance = brlc.balanceOf(address(this)); if (balance > 0) { require( brlc.transfer(msg.sender, balance), "V2_1Upgrader: failed to withdraw BRLC" ); } } /** * @notice Transfer proxy admin role to newProxyAdmin, and self-destruct */ function abortUpgrade() external onlyOwner { // Transfer proxy admin role _proxy.changeAdmin(_newProxyAdmin); // Tear down _helper.tearDown(); selfdestruct(msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev 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 * * Copyright (c) 2018 zOS Global Limited. * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @notice The Ownable contract has an owner address, and provides basic * authorization control functions * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol * Modifications: * 1. Consolidate OwnableStorage into this contract (7/13/18) * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 3. Make public functions external (5/27/20) */ contract Ownable { // Owner of the contract address private _owner; /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The constructor sets the original owner of the contract to the sender account. */ constructor() public { setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() external view returns (address) { return _owner; } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { _owner = newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == _owner, "Ownable: caller is not the owner"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); setOwner(newOwner); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { FiatTokenV2 } from "./FiatTokenV2.sol"; // solhint-disable func-name-mixedcase /** * @title FiatToken V2.1 * @notice ERC20 Token backed by fiat reserves, version 2.1 */ contract FiatTokenV2_1 is FiatTokenV2 { /** * @notice Initialize v2.1 * @param lostAndFound The address to which the locked funds are sent */ function initializeV2_1(address lostAndFound) external { // solhint-disable-next-line reason-string require(_initializedVersion == 1); uint256 lockedAmount = balances[address(this)]; if (lockedAmount > 0) { _transfer(address(this), lostAndFound, lockedAmount); } blacklisted[address(this)] = true; _initializedVersion = 2; } /** * @notice Version string for the EIP712 domain separator * @return Version string */ function version() external view returns (string memory) { return "2"; } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { AdminUpgradeabilityProxy } from "../upgradeability/AdminUpgradeabilityProxy.sol"; /** * @title FiatTokenProxy * @dev This contract proxies FiatToken calls and enables FiatToken upgrades */ contract FiatTokenProxy is AdminUpgradeabilityProxy { constructor(address implementationContract) public AdminUpgradeabilityProxy(implementationContract) {} } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { FiatTokenV1 } from "../../v1/FiatTokenV1.sol"; import { Ownable } from "../../v1/Ownable.sol"; /** * @title V2 Upgrader Helper * @dev Enables V2Upgrader to read some contract state before it renounces the * proxy admin role. (Proxy admins cannot call delegated methods.) It is also * used to test approve/transferFrom. */ contract V2UpgraderHelper is Ownable { address private _proxy; /** * @notice Constructor * @param fiatTokenProxy Address of the FiatTokenProxy contract */ constructor(address fiatTokenProxy) public Ownable() { _proxy = fiatTokenProxy; } /** * @notice The address of the FiatTokenProxy contract * @return Contract address */ function proxy() external view returns (address) { return address(_proxy); } /** * @notice Call name() * @return name */ function name() external view returns (string memory) { return FiatTokenV1(_proxy).name(); } /** * @notice Call symbol() * @return symbol */ function symbol() external view returns (string memory) { return FiatTokenV1(_proxy).symbol(); } /** * @notice Call decimals() * @return decimals */ function decimals() external view returns (uint8) { return FiatTokenV1(_proxy).decimals(); } /** * @notice Call currency() * @return currency */ function currency() external view returns (string memory) { return FiatTokenV1(_proxy).currency(); } /** * @notice Call masterMinter() * @return masterMinter */ function masterMinter() external view returns (address) { return FiatTokenV1(_proxy).masterMinter(); } /** * @notice Call owner() * @dev Renamed to fiatTokenOwner due to the existence of Ownable.owner() * @return owner */ function fiatTokenOwner() external view returns (address) { return FiatTokenV1(_proxy).owner(); } /** * @notice Call pauser() * @return pauser */ function pauser() external view returns (address) { return FiatTokenV1(_proxy).pauser(); } /** * @notice Call blacklister() * @return blacklister */ function blacklister() external view returns (address) { return FiatTokenV1(_proxy).blacklister(); } /** * @notice Call balanceOf(address) * @param account Account * @return balance */ function balanceOf(address account) external view returns (uint256) { return FiatTokenV1(_proxy).balanceOf(account); } /** * @notice Call transferFrom(address,address,uint256) * @param from Sender * @param to Recipient * @param value Amount * @return result */ function transferFrom( address from, address to, uint256 value ) external returns (bool) { return FiatTokenV1(_proxy).transferFrom(from, to, value); } /** * @notice Tear down the contract (self-destruct) */ function tearDown() external onlyOwner { selfdestruct(msg.sender); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { FiatTokenV1_1 } from "../v1.1/FiatTokenV1_1.sol"; import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol"; import { EIP712 } from "../util/EIP712.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP3009 } from "./EIP3009.sol"; import { EIP2612 } from "./EIP2612.sol"; /** * @title FiatToken V2 * @notice ERC20 Token backed by fiat reserves, version 2 */ contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 { uint8 internal _initializedVersion; /** * @notice Initialize v2 * @param newName New token name */ function initializeV2(string calldata newName) external { // solhint-disable-next-line reason-string require(initialized && _initializedVersion == 0); name = newName; DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(newName, "2"); _initializedVersion = 1; } /** * @notice Increase the allowance by a given increment * @param spender Spender's address * @param increment Amount of increase in allowance * @return True if successful */ function increaseAllowance(address spender, uint256 increment) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _increaseAllowance(msg.sender, spender, increment); return true; } /** * @notice Decrease the allowance by a given decrement * @param spender Spender's address * @param decrement Amount of decrease in allowance * @return True if successful */ function decreaseAllowance(address spender, uint256 decrement) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _decreaseAllowance(msg.sender, spender, decrement); return true; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) { _transferWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) { _receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Attempt to cancel an authorization * @dev Works only if the authorization is not yet used. * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused { _cancelAuthorization(authorizer, nonce, v, r, s); } /** * @notice Update allowance with a signed permit * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline Expiration time, seconds since the epoch * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) { _permit(owner, spender, value, deadline, v, r, s); } /** * @notice Internal function to increase the allowance by a given increment * @param owner Token owner's address * @param spender Spender's address * @param increment Amount of increase */ function _increaseAllowance( address owner, address spender, uint256 increment ) internal override { _approve(owner, spender, allowed[owner][spender].add(increment)); } /** * @notice Internal function to decrease the allowance by a given decrement * @param owner Token owner's address * @param spender Spender's address * @param decrement Amount of decrease */ function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal override { _approve( owner, spender, allowed[owner][spender].sub( decrement, "ERC20: decreased allowance below zero" ) ); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { FiatTokenV1 } from "../v1/FiatTokenV1.sol"; import { Rescuable } from "./Rescuable.sol"; /** * @title FiatTokenV1_1 * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1_1 is FiatTokenV1, Rescuable { } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { AbstractFiatTokenV1 } from "../v1/AbstractFiatTokenV1.sol"; abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 { function _increaseAllowance( address owner, address spender, uint256 increment ) internal virtual; function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal virtual; } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { ECRecover } from "./ECRecover.sol"; /** * @title EIP712 * @notice A library that provides EIP712 helper functions */ library EIP712 { /** * @notice Make EIP712 domain separator * @param name Contract name * @param version Contract version * @return Domain separator */ function makeDomainSeparator(string memory name, string memory version) internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return keccak256( abi.encode( // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /** * @notice Recover signer's address from a EIP712 signature * @param domainSeparator Domain separator * @param v v of the signature * @param r r of the signature * @param s s of the signature * @param typeHashAndData Type hash concatenated with data * @return Signer's address */ function recover( bytes32 domainSeparator, uint8 v, bytes32 r, bytes32 s, bytes memory typeHashAndData ) internal pure returns (address) { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256(typeHashAndData) ) ); return ECRecover.recover(digest, v, r, s); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title EIP712 Domain */ contract EIP712Domain { /** * @dev EIP712 Domain Separator */ bytes32 public DOMAIN_SEPARATOR; } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP712 } from "../util/EIP712.sol"; /** * @title EIP-3009 * @notice Provide internal implementation for gas-abstracted transfers * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain { // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; /** * @dev authorizer address => nonce => bool (true if nonce is used) */ mapping(address => mapping(bytes32 => bool)) private _authorizationStates; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled( address indexed authorizer, bytes32 indexed nonce ); /** * @notice Returns the state of an authorization * @dev Nonces are randomly generated 32-byte data unique to the * authorizer's address * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return True if the nonce is used */ function authorizationState(address authorizer, bytes32 nonce) external view returns (bool) { return _authorizationStates[authorizer][nonce]; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { require(to == msg.sender, "FiatTokenV2: caller must be the payee"); _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode( CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer, "FiatTokenV2: invalid signature" ); _authorizationStates[authorizer][nonce] = true; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( !_authorizationStates[authorizer][nonce], "FiatTokenV2: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require( now > validAfter, "FiatTokenV2: authorization is not yet valid" ); require(now < validBefore, "FiatTokenV2: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { _authorizationStates[authorizer][nonce] = true; emit AuthorizationUsed(authorizer, nonce); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP712 } from "../util/EIP712.sol"; /** * @title EIP-2612 * @notice Provide internal implementation for gas-abstracted approvals */ abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain { // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) private _permitNonces; /** * @notice Nonces for permit * @param owner Token owner's address (Authorizer) * @return Next nonce */ function nonces(address owner) external view returns (uint256) { return _permitNonces[owner]; } /** * @notice Verify a signed approval permit and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline The time at which this expires (unix time) * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { require(deadline >= now, "FiatTokenV2: permit is expired"); bytes memory data = abi.encode( PERMIT_TYPEHASH, owner, spender, value, _permitNonces[owner]++, deadline ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner, "EIP2612: invalid signature" ); _approve(owner, spender, value); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { AbstractFiatTokenV1 } from "./AbstractFiatTokenV1.sol"; import { Ownable } from "./Ownable.sol"; import { Pausable } from "./Pausable.sol"; import { Blacklistable } from "./Blacklistable.sol"; /** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string memory tokenName, string memory tokenSymbol, string memory tokenCurrency, uint8 tokenDecimals, address newMasterMinter, address newPauser, address newBlacklister, address newOwner ) public { require(!initialized, "FiatToken: contract is already initialized"); require( newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); require( newPauser != address(0), "FiatToken: new pauser is the zero address" ); require( newBlacklister != address(0), "FiatToken: new blacklister is the zero address" ); require( newOwner != address(0), "FiatToken: new owner is the zero address" ); name = tokenName; symbol = tokenSymbol; currency = tokenCurrency; decimals = tokenDecimals; masterMinter = newMasterMinter; pauser = newPauser; blacklister = newBlacklister; setOwner(newOwner); initialized = true; } /** * @dev Throws if called by any account other than a minter */ modifier onlyMinters() { require(minters[msg.sender], "FiatToken: caller is not a minter"); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. Must be less than or equal * to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) returns (bool) { require(_to != address(0), "FiatToken: mint to the zero address"); require(_amount > 0, "FiatToken: mint amount not greater than 0"); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require( _amount <= mintingAllowedAmount, "FiatToken: mint amount exceeds minterAllowance" ); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Throws if called by any account other than the masterMinter */ modifier onlyMasterMinter() { require( msg.sender == masterMinter, "FiatToken: caller is not the masterMinter" ); _; } /** * @dev Get minter allowance for an account * @param minter The address of the minter */ function minterAllowance(address minter) external view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks if account is a minter * @param account The address to check */ function isMinter(address account) external view returns (bool) { return minters[account]; } /** * @notice Amount of remaining tokens spender is allowed to transfer on * behalf of the token owner * @param owner Token owner's address * @param spender Spender's address * @return Allowance amount */ function allowance(address owner, address spender) external override view returns (uint256) { return allowed[owner][spender]; } /** * @dev Get totalSupply of token */ function totalSupply() external override view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * @param account address The account */ function balanceOf(address account) external override view returns (uint256) { return balances[account]; } /** * @notice Set spender's allowance over the caller's tokens to be a given * value. * @param spender Spender's address * @param value Allowance amount * @return True if successful */ function approve(address spender, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Internal function to set allowance * @param owner Token owner's address * @param spender Spender's address * @param value Allowance amount */ function _approve( address owner, address spender, uint256 value ) internal override { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @notice Transfer tokens by spending allowance * @param from Payer's address * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transferFrom( address from, address to, uint256 value ) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(from) notBlacklisted(to) returns (bool) { require( value <= allowed[from][msg.sender], "ERC20: transfer amount exceeds allowance" ); _transfer(from, to, value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); return true; } /** * @notice Transfer tokens from the caller * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transfer(address to, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(to) returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @notice Internal function to process transfers * @param from Payer's address * @param to Payee's address * @param value Transfer amount */ function _transfer( address from, address to, uint256 value ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require( value <= balances[from], "ERC20: transfer amount exceeds balance" ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Function to add/update a new minter * @param minter The address of the minter * @param minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) external whenNotPaused onlyMasterMinter returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * @param minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) external onlyMasterMinter returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter's account balance * @param _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) { uint256 balance = balances[msg.sender]; require(_amount > 0, "FiatToken: burn amount not greater than 0"); require(balance >= _amount, "FiatToken: burn amount exceeds balance"); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) external onlyOwner { require( _newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { Ownable } from "../v1/Ownable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract Rescuable is Ownable { using SafeERC20 for IERC20; address private _rescuer; event RescuerChanged(address indexed newRescuer); /** * @notice Returns current rescuer * @return Rescuer's address */ function rescuer() external view returns (address) { return _rescuer; } /** * @notice Revert if called by any account other than the rescuer. */ modifier onlyRescuer() { require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer"); _; } /** * @notice Rescue ERC20 tokens locked up in this contract. * @param tokenContract ERC20 token contract address * @param to Recipient address * @param amount Amount to withdraw */ function rescueERC20( IERC20 tokenContract, address to, uint256 amount ) external onlyRescuer { tokenContract.safeTransfer(to, amount); } /** * @notice Assign the rescuer role to a given address. * @param newRescuer New rescuer's address */ function updateRescuer(address newRescuer) external onlyOwner { require( newRescuer != address(0), "Rescuable: new rescuer is the zero address" ); _rescuer = newRescuer; emit RescuerChanged(newRescuer); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; abstract contract AbstractFiatTokenV1 is IERC20 { function _approve( address owner, address spender, uint256 value ) internal virtual; function _transfer( address from, address to, uint256 value ) internal virtual; } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2016 Smart Contract Solutions, Inc. * Copyright (c) 2018-2020 CENTRE SECZ0 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { Ownable } from "./Ownable.sol"; /** * @notice Base contract which allows children to implement an emergency stop * mechanism * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol * Modifications: * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018) * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018) * 3. Removed whenPaused (6/14/2018) * 4. Switches ownable library to use ZeppelinOS (7/12/18) * 5. Remove constructor (7/13/18) * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20) * 7. Make public functions external (5/27/20) */ contract Pausable is Ownable { event Pause(); event Unpause(); event PauserChanged(address indexed newAddress); address public pauser; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "Pausable: paused"); _; } /** * @dev throws if called by any account other than the pauser */ modifier onlyPauser() { require(msg.sender == pauser, "Pausable: caller is not the pauser"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() external onlyPauser { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() external onlyPauser { paused = false; emit Unpause(); } /** * @dev update the pauser role */ function updatePauser(address _newPauser) external onlyOwner { require( _newPauser != address(0), "Pausable: new pauser is the zero address" ); pauser = _newPauser; emit PauserChanged(pauser); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { Ownable } from "./Ownable.sol"; /** * @title Blacklistable Token * @dev Allows accounts to be blacklisted by a "blacklister" role */ contract Blacklistable is Ownable { address public blacklister; mapping(address => bool) internal blacklisted; event Blacklisted(address indexed _account); event UnBlacklisted(address indexed _account); event BlacklisterChanged(address indexed newBlacklister); /** * @dev Throws if called by any account other than the blacklister */ modifier onlyBlacklister() { require( msg.sender == blacklister, "Blacklistable: caller is not the blacklister" ); _; } /** * @dev Throws if argument account is blacklisted * @param _account The address to check */ modifier notBlacklisted(address _account) { require( !blacklisted[_account], "Blacklistable: account is blacklisted" ); _; } /** * @dev Checks if account is blacklisted * @param _account The address to check */ function isBlacklisted(address _account) external view returns (bool) { return blacklisted[_account]; } /** * @dev Adds account to blacklist * @param _account The address to blacklist */ function blacklist(address _account) external onlyBlacklister { blacklisted[_account] = true; emit Blacklisted(_account); } /** * @dev Removes account from blacklist * @param _account The address to remove from the blacklist */ function unBlacklist(address _account) external onlyBlacklister { blacklisted[_account] = false; emit UnBlacklisted(_account); } function updateBlacklister(address _newBlacklister) external onlyOwner { require( _newBlacklister != address(0), "Blacklistable: new blacklister is the zero address" ); blacklister = _newBlacklister; emit BlacklisterChanged(blacklister); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2016-2019 zOS Global Limited * Copyright (c) 2018-2020 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library ECRecover { /** * @notice Recover signer's address from a signed message * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol * Modifications: Accept v, r, and s as separate arguments * @param digest Keccak-256 hash digest of the signed message * @param v v of the signature * @param r r of the signature * @param s s of the signature * @return Signer address */ function recover( bytes32 digest, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { revert("ECRecover: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECRecover: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(digest, v, r, s); require(signer != address(0), "ECRecover: invalid signature"); return signer; } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { UpgradeabilityProxy } from "./UpgradeabilityProxy.sol"; /** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */ contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { Proxy } from "./Proxy.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; /** * @notice This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/UpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Use Address utility library from the latest OpenZeppelin (5/13/20) */ contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param implementationContract Address of the initial implementation. */ constructor(address implementationContract) public { assert( IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation") ); _setImplementation(implementationContract); } /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @notice Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/Proxy.sol * Modifications: * 1. Reformat and conform to Solidity 0.6 syntax (5/13/20) */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
Withdraw any BRLC in the contract/
function withdrawBRLC() public onlyOwner { IERC20 brlc = IERC20(address(_proxy)); uint256 balance = brlc.balanceOf(address(this)); if (balance > 0) { require( brlc.transfer(msg.sender, balance), "V2_1Upgrader: failed to withdraw BRLC" ); } }
1,098,309
./partial_match/3/0xD0D14e32105E95058a28d8753eF930B024ee38eE/sources/SpotLogic.sol
Verifies the inclusion of a leaf is at a specific place in an ordered Merkle tree using a Merkle proof /
function verifyIncludedAtIndex(bytes memory proof, bytes32 root, bytes32 leaf, uint index) public pure returns (bool) { return checkProofOrdered(proof, root, leaf, index); }
5,086,594
pragma solidity 0.6.11; // SPDX-License-Identifier: BSD-3-Clause /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /** * @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.3._ */ 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.3._ */ 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 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); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface IUniswapV2Router { 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 removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Pair { 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 token0() external view returns (address); function token1() external view returns (address); function sync() external; } interface StakingContract { function depositByContract(address account, uint amount, uint _amountOutMin_stakingReferralFee, uint deadline) external; } /** * @dev Staking Smart Contract * * - Users stake Uniswap LP Tokens to receive WETH and DYP Tokens as Rewards * * - Reward Tokens (DYP) are added to contract balance upon deployment by deployer * * - After Adding the DYP rewards, admin is supposed to transfer ownership to Governance contract * * - Users deposit Set (Predecided) Uniswap LP Tokens and get a share of the farm * * - The smart contract disburses `disburseAmount` DYP as rewards over `disburseDuration` * * - A swap is attempted periodically at atleast a set delay from last swap * * - The swap is attempted according to SWAP_PATH for difference deployments of this contract * * - For 4 different deployments of this contract, the SWAP_PATH will be: * - DYP-WETH * - DYP-WBTC-WETH (assumes appropriate liquidity is available in WBTC-WETH pair) * - DYP-USDT-WETH (assumes appropriate liquidity is available in USDT-WETH pair) * - DYP-USDC-WETH (assumes appropriate liquidity is available in USDC-WETH pair) * * - Any swap may not have a price impact on DYP price of more than approx ~2.49% for the related DYP pair * DYP-WETH swap may not have a price impact of more than ~2.49% on DYP price in DYP-WETH pair * DYP-WBTC-WETH swap may not have a price impact of more than ~2.49% on DYP price in DYP-WBTC pair * DYP-USDT-WETH swap may not have a price impact of more than ~2.49% on DYP price in DYP-USDT pair * DYP-USDC-WETH swap may not have a price impact of more than ~2.49% on DYP price in DYP-USDC pair * * - After the swap,converted WETH is distributed to stakers at pro-rata basis, according to their share of the staking pool * on the moment when the WETH distribution is done. And remaining DYP is added to the amount to be distributed or burnt. * The remaining DYP are also attempted to be swapped to WETH in the next swap if the price impact is ~2.49% or less * * - At a set delay from last execution, Governance contract (owner) may execute disburse or burn features * * - Burn feature should send the DYP tokens to set BURN_ADDRESS * * - Disburse feature should disburse the DYP * (which would have a max price impact ~2.49% if it were to be swapped, at disburse time * - remaining DYP are sent to BURN_ADDRESS) * to stakers at pro-rata basis according to their share of * the staking pool at the moment the disburse is done * * - Users may claim their pending WETH and DYP anytime * * - Pending rewards are auto-claimed on any deposit or withdraw * * - Users need to wait `cliffTime` duration since their last deposit before withdrawing any LP Tokens * * - Owner may not transfer out LP Tokens from this contract anytime * * - Owner may transfer out WETH and DYP Tokens from this contract once `adminClaimableTime` is reached * * - CONTRACT VARIABLES must be changed to appropriate values before live deployment */ contract FarmProRata is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; using Address for address; using SafeERC20 for IERC20; event RewardsTransferred(address holder, uint amount); event EthRewardsTransferred(address holder, uint amount); event RewardsDisbursed(uint amount); event EthRewardsDisbursed(uint amount); event EmergencyDeclared(address owner); event UniswapV2RouterChanged(address router); event StakingFeeChanged(uint fee); event UnstakingFeeChanged(uint fee); event MagicNumberChanged(uint newMagicNumber); event LockupTimeChanged(uint lockupTime); event FeeRecipientAddressChanged(address newAddress); // ============ SMART CONTRACT VARIABLES ========================== // Must be changed to appropriate configuration before live deployment // deposit token contract address and reward token contract address // these contracts (and uniswap pair & router) are "trusted" // and checked to not contain re-entrancy pattern // to safely avoid checks-effects-interactions where needed to simplify logic address public constant trustedDepositTokenAddress = 0x7463286A379F6F128058bb92B355e3d6E8BDB219; // uniswap pair address // token used for rewards - this must be one of the tokens in uniswap pair. address public constant trustedRewardTokenAddress = 0xBD100d061E120b2c67A24453CF6368E63f1Be056; address public constant trustedStakingContractAddress = 0xb67F464b558e3055C2B6F017546Ed53b2e6333d7; // the main token which is normally claimed as reward address public constant trustedPlatformTokenAddress = 0x961C8c0B1aaD0c0b10a51FeF6a867E3091BCef17; // the other token in the uniswap pair used address public constant trustedBaseTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Make sure to double-check BURN_ADDRESS address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; // cliffTime - withdraw is not possible within cliffTime of deposit uint public cliffTime = 60 days; // Amount of tokens uint public constant disburseAmount = 2220000e18; // To be disbursed continuously over this duration uint public constant disburseDuration = 365 days; // If there are any undistributed or unclaimed tokens left in contract after this time // Admin can claim them uint public constant adminCanClaimAfter = 395 days; // delays between attempted swaps uint public constant swapAttemptPeriod = 1 days; // delays between attempted burns or token disbursement uint public constant burnOrDisburseTokensPeriod = 7 days; // do not change this => disburse 100% rewards over `disburseDuration` uint public constant disbursePercentX100 = 100e2; uint public constant EMERGENCY_WAIT_TIME = 3 days; uint public STAKING_FEE_RATE_X_100 = 0; uint public UNSTAKING_FEE_RATE_X_100 = 0; uint public MAGIC_NUMBER = 5025125628140614; // ============ END CONTRACT VARIABLES ========================== event ClaimableTokenAdded(address indexed tokenAddress); event ClaimableTokenRemoved(address indexed tokenAddress); mapping (address => bool) public trustedClaimableTokens; function addTrustedClaimableToken(address trustedClaimableTokenAddress) external onlyOwner { trustedClaimableTokens[trustedClaimableTokenAddress] = true; emit ClaimableTokenAdded(trustedClaimableTokenAddress); } function removeTrustedClaimableToken(address trustedClaimableTokenAddress) external onlyOwner { trustedClaimableTokens[trustedClaimableTokenAddress] = false; emit ClaimableTokenRemoved(trustedClaimableTokenAddress); } uint public contractDeployTime; uint public adminClaimableTime; uint public lastDisburseTime; uint public lastSwapExecutionTime; uint public lastBurnOrTokenDistributeTime; bool public isEmergency = false; IUniswapV2Router public uniswapRouterV2; IUniswapV2Pair public uniswapV2Pair; address[] public SWAP_PATH; address public feeRecipientAddress; constructor(address[] memory swapPath, address _uniswapV2RouterAddress, address _feeRecipientAddress) public { contractDeployTime = now; adminClaimableTime = contractDeployTime.add(adminCanClaimAfter); lastDisburseTime = contractDeployTime; lastSwapExecutionTime = lastDisburseTime; lastBurnOrTokenDistributeTime = lastDisburseTime; setUniswapV2Router(IUniswapV2Router(_uniswapV2RouterAddress)); setFeeRecipientAddress(_feeRecipientAddress); uniswapV2Pair = IUniswapV2Pair(trustedDepositTokenAddress); SWAP_PATH = swapPath; } function setFeeRecipientAddress(address newFeeRecipientAddress) public onlyOwner { require(newFeeRecipientAddress != address(0), "Invalid address!"); feeRecipientAddress = newFeeRecipientAddress; emit FeeRecipientAddressChanged(feeRecipientAddress); } // Contracts are not allowed to deposit, claim or withdraw modifier noContractsAllowed() { require(!(address(msg.sender).isContract()) && tx.origin == msg.sender, "No Contracts Allowed!"); _; } modifier notDuringEmergency() { require(!isEmergency, "Cannot execute during emergency!"); _; } function declareEmergency() external onlyOwner notDuringEmergency { isEmergency = true; adminClaimableTime = now.add(EMERGENCY_WAIT_TIME); cliffTime = 0; emit EmergencyDeclared(owner); } uint public totalClaimedRewards = 0; uint public totalClaimedRewardsEth = 0; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public depositTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; mapping (address => uint) public totalEarnedEth; mapping (address => uint) public lastDivPoints; mapping (address => uint) public lastEthDivPoints; uint public contractBalance = 0; uint public totalDivPoints = 0; uint public totalEthDivPoints = 0; uint public totalTokens = 0; uint public tokensToBeDisbursedOrBurnt = 0; uint public tokensToBeSwapped = 0; uint internal constant pointMultiplier = 1e18; function setUniswapV2Router(IUniswapV2Router router) public onlyOwner { require(address(router) != address(0), "Invalid router address!"); uniswapRouterV2 = router; emit UniswapV2RouterChanged(address(uniswapRouterV2)); } function setStakingFeeRateX100(uint newStakingFeeRateX100) public onlyOwner { require(newStakingFeeRateX100 < 100e2, "Invalid fee!"); STAKING_FEE_RATE_X_100 = newStakingFeeRateX100; emit StakingFeeChanged(STAKING_FEE_RATE_X_100); } function setUnstakingFeeRateX100(uint newUnstakingFeeRateX100) public onlyOwner { require(newUnstakingFeeRateX100 < 100e2, "Invalid fee!"); UNSTAKING_FEE_RATE_X_100 = newUnstakingFeeRateX100; emit UnstakingFeeChanged(UNSTAKING_FEE_RATE_X_100); } function setMagicNumber(uint newMagicNumber) public onlyOwner { MAGIC_NUMBER = newMagicNumber; emit MagicNumberChanged(MAGIC_NUMBER); } function setLockupTime(uint _newLockupTime) public onlyOwner { require(_newLockupTime <= 90 days, "Lockup time too long!"); cliffTime = _newLockupTime; emit LockupTimeChanged(cliffTime); } function setContractVariables( uint newMagicNumber, uint lockupTime, uint stakingFeeRateX100, uint unstakingFeeRateX100, address _uniswapV2RouterAddress, address newFeeRecipientAddress ) external onlyOwner { setMagicNumber(newMagicNumber); setLockupTime(lockupTime); setStakingFeeRateX100(stakingFeeRateX100); setUnstakingFeeRateX100(unstakingFeeRateX100); setUniswapV2Router(IUniswapV2Router(_uniswapV2RouterAddress)); setFeeRecipientAddress(newFeeRecipientAddress); } // To be executed by admin after deployment to add DYP to contract function addContractBalance(uint amount) public onlyOwner { IERC20(trustedRewardTokenAddress).safeTransferFrom(msg.sender, address(this), amount); contractBalance = contractBalance.add(amount); } function doSwap(address fromToken, address toToken, uint fromTokenAmount, uint amountOutMin, uint deadline) private returns (uint _toTokenReceived) { if (fromToken == toToken) { return fromTokenAmount; } IERC20(fromToken).safeApprove(address(uniswapRouterV2), 0); IERC20(fromToken).safeApprove(address(uniswapRouterV2), fromTokenAmount); uint oldToTokenBalance = IERC20(toToken).balanceOf(address(this)); address[] memory path; if (fromToken == uniswapRouterV2.WETH() || toToken == uniswapRouterV2.WETH()) { path = new address[](2); path[0] = fromToken; path[1] = toToken; } else { path = new address[](3); path[0] = fromToken; path[1] = uniswapRouterV2.WETH(); path[2] = toToken; } uniswapRouterV2.swapExactTokensForTokens(fromTokenAmount, amountOutMin, path, address(this), deadline); uint newToTokenBalance = IERC20(toToken).balanceOf(address(this)); uint toTokenReceived = newToTokenBalance.sub(oldToTokenBalance); return toTokenReceived; } // Private function to update account information and auto-claim pending rewards function updateAccount( address account, address claimAsToken, uint _amountOutMin_claimAsToken_weth, uint _amountOutMin_claimAsToken_dyp, uint _amountOutMin_attemptSwap, uint _deadline ) private { disburseTokens(); attemptSwap(_amountOutMin_attemptSwap, _deadline); uint pendingDivs = getPendingDivs(account); if (pendingDivs > 0) { uint amountToTransfer; address tokenToTransfer; if (claimAsToken == address(0) || claimAsToken == trustedPlatformTokenAddress) { tokenToTransfer = trustedPlatformTokenAddress; amountToTransfer = doSwap(trustedRewardTokenAddress, trustedPlatformTokenAddress, pendingDivs, _amountOutMin_claimAsToken_dyp, _deadline); } else { tokenToTransfer = claimAsToken; amountToTransfer = doSwap(trustedRewardTokenAddress, claimAsToken, pendingDivs, _amountOutMin_claimAsToken_dyp, _deadline); } IERC20(tokenToTransfer).safeTransfer(account, amountToTransfer); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); emit RewardsTransferred(account, pendingDivs); } uint pendingDivsEth = getPendingDivsEth(account); if (pendingDivsEth > 0) { if (claimAsToken == address(0) || claimAsToken == uniswapRouterV2.WETH()) { IERC20(uniswapRouterV2.WETH()).safeTransfer(account, pendingDivsEth); } else { require(trustedClaimableTokens[claimAsToken], "cannot claim as this token!"); IERC20(uniswapRouterV2.WETH()).safeApprove(address(uniswapRouterV2), 0); IERC20(uniswapRouterV2.WETH()).safeApprove(address(uniswapRouterV2), pendingDivsEth); address[] memory path = new address[](2); path[0] = uniswapRouterV2.WETH(); path[1] = claimAsToken; uniswapRouterV2.swapExactTokensForTokens(pendingDivsEth, _amountOutMin_claimAsToken_weth, path, account, _deadline); } totalEarnedEth[account] = totalEarnedEth[account].add(pendingDivsEth); totalClaimedRewardsEth = totalClaimedRewardsEth.add(pendingDivsEth); emit EthRewardsTransferred(account, pendingDivsEth); } lastClaimedTime[account] = now; lastDivPoints[account] = totalDivPoints; lastEthDivPoints[account] = totalEthDivPoints; } function updateAccount(address account, uint _amountOutMin_claimAsToken_dyp, uint _amountOutMin_attemptSwap, uint _deadline) private { updateAccount(account, address(0), 0, _amountOutMin_claimAsToken_dyp, _amountOutMin_attemptSwap, _deadline); } // view function to check last updated DYP pending rewards function getPendingDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint newDivPoints = totalDivPoints.sub(lastDivPoints[_holder]); uint depositedAmount = depositedTokens[_holder]; uint pendingDivs = depositedAmount.mul(newDivPoints).div(pointMultiplier); return pendingDivs; } // view function to check last updated WETH pending rewards function getPendingDivsEth(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint newDivPoints = totalEthDivPoints.sub(lastEthDivPoints[_holder]); uint depositedAmount = depositedTokens[_holder]; uint pendingDivs = depositedAmount.mul(newDivPoints).div(pointMultiplier); return pendingDivs; } // view functon to get number of stakers function getNumberOfHolders() public view returns (uint) { return holders.length(); } // deposit function to stake LP Tokens function deposit( address depositToken, uint amountToStake, uint[] memory minAmounts, // uint _amountOutMin_25Percent, // 0 // uint _amountOutMin_stakingReferralFee, // 1 // uint amountLiquidityMin_rewardTokenReceived, // 2 // uint amountLiquidityMin_baseTokenReceived, // 3 // uint _amountOutMin_rewardTokenReceived, // 4 // uint _amountOutMin_baseTokenReceived, // 5 // uint _amountOutMin_claimAsToken_dyp, // 6 // uint _amountOutMin_attemptSwap, // 7 uint _deadline ) public noContractsAllowed notDuringEmergency { require(minAmounts.length == 8, "Invalid minAmounts length!"); require(trustedClaimableTokens[depositToken], "Invalid deposit token!"); // can deposit reward token directly // require(depositToken != trustedRewardTokenAddress, "Cannot deposit reward token!"); require(depositToken != trustedDepositTokenAddress, "Cannot deposit LP directly!"); require(depositToken != address(0), "Deposit token cannot be 0!"); require(amountToStake > 0, "Invalid amount to Stake!"); IERC20(depositToken).safeTransferFrom(msg.sender, address(this), amountToStake); uint fee = amountToStake.mul(STAKING_FEE_RATE_X_100).div(100e2); uint amountAfterFee = amountToStake.sub(fee); if (fee > 0) { IERC20(depositToken).safeTransfer(feeRecipientAddress, fee); } uint _75Percent = amountAfterFee.mul(75e2).div(100e2); uint _25Percent = amountAfterFee.sub(_75Percent); uint amountToDepositByContract = doSwap(depositToken, trustedPlatformTokenAddress, _25Percent, /*_amountOutMin_25Percent*/minAmounts[0], _deadline); IERC20(trustedPlatformTokenAddress).safeApprove(address(trustedStakingContractAddress), 0); IERC20(trustedPlatformTokenAddress).safeApprove(address(trustedStakingContractAddress), amountToDepositByContract); StakingContract(trustedStakingContractAddress).depositByContract(msg.sender, amountToDepositByContract, /*_amountOutMin_stakingReferralFee*/minAmounts[1], _deadline); uint half = _75Percent.div(2); uint otherHalf = _75Percent.sub(half); uint _rewardTokenReceived = doSwap(depositToken, trustedRewardTokenAddress, half, /*_amountOutMin_rewardTokenReceived*/minAmounts[4], _deadline); uint _baseTokenReceived = doSwap(depositToken, trustedBaseTokenAddress, otherHalf, /*_amountOutMin_baseTokenReceived*/minAmounts[5], _deadline); uint amountToDeposit = addLiquidityAndGetAmountToDeposit( _rewardTokenReceived, _baseTokenReceived, minAmounts, _deadline ); require(amountToDeposit > 0, "Cannot deposit 0 Tokens"); updateAccount(msg.sender, /*_amountOutMin_claimAsToken_dyp*/minAmounts[6], /*_amountOutMin_attemptSwap*/minAmounts[7], _deadline); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToDeposit); totalTokens = totalTokens.add(amountToDeposit); holders.add(msg.sender); depositTime[msg.sender] = now; } function addLiquidityAndGetAmountToDeposit( uint _rewardTokenReceived, uint _baseTokenReceived, uint[] memory minAmounts, uint _deadline ) private returns (uint) { require(_rewardTokenReceived >= minAmounts[2], "Reward Token Received lower than expected!"); require(_baseTokenReceived >= minAmounts[3], "Base Token Received lower than expected!"); uint oldLpBalance = IERC20(trustedDepositTokenAddress).balanceOf(address(this)); IERC20(trustedRewardTokenAddress).safeApprove(address(uniswapRouterV2), 0); IERC20(trustedRewardTokenAddress).safeApprove(address(uniswapRouterV2), _rewardTokenReceived); IERC20(trustedBaseTokenAddress).safeApprove(address(uniswapRouterV2), 0); IERC20(trustedBaseTokenAddress).safeApprove(address(uniswapRouterV2), _baseTokenReceived); uniswapRouterV2.addLiquidity( trustedRewardTokenAddress, trustedBaseTokenAddress, _rewardTokenReceived, _baseTokenReceived, /*amountLiquidityMin_rewardTokenReceived*/minAmounts[2], /*amountLiquidityMin_baseTokenReceived*/minAmounts[3], address(this), _deadline ); uint newLpBalance = IERC20(trustedDepositTokenAddress).balanceOf(address(this)); uint lpTokensReceived = newLpBalance.sub(oldLpBalance); return lpTokensReceived; } // withdraw function to unstake LP Tokens function withdraw( address withdrawAsToken, uint amountToWithdraw, uint[] memory minAmounts, // uint _amountLiquidityMin_rewardToken, // 0 // uint _amountLiquidityMin_baseToken, // 1 // uint _amountOutMin_withdrawAsToken_rewardTokenReceived, // 2 // uint _amountOutMin_withdrawAsToken_baseTokenReceived, // 3 // uint _amountOutMin_claimAsToken_dyp, // 4 // uint _amountOutMin_attemptSwap, // 5 uint _deadline ) public noContractsAllowed { require(minAmounts.length == 6, "Invalid minAmounts!"); require(withdrawAsToken != address(0), "Invalid withdraw token!"); require(trustedClaimableTokens[withdrawAsToken], "Withdraw token not trusted!"); require(amountToWithdraw > 0, "Cannot withdraw 0 Tokens!"); require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(depositTime[msg.sender]) > cliffTime, "You recently deposited, please wait before withdrawing."); updateAccount(msg.sender, /*_amountOutMin_claimAsToken_dyp*/ minAmounts[4] , /*_amountOutMin_attemptSwap*/ minAmounts[5], _deadline); uint fee = amountToWithdraw.mul(UNSTAKING_FEE_RATE_X_100).div(100e2); uint amountAfterFee = amountToWithdraw.sub(fee); if (fee > 0) { IERC20(trustedDepositTokenAddress).safeTransfer(feeRecipientAddress, fee); } uint withdrawTokenReceived = removeLiquidityAndGetWithdrawTokenReceived(withdrawAsToken, amountAfterFee, minAmounts, _deadline); IERC20(withdrawAsToken).safeTransfer(msg.sender, withdrawTokenReceived); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); totalTokens = totalTokens.sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function removeLiquidityAndGetWithdrawTokenReceived( address withdrawAsToken, uint amountAfterFee, uint[] memory minAmounts, uint _deadline ) private returns (uint) { IERC20(trustedDepositTokenAddress).safeApprove(address(uniswapRouterV2), 0); IERC20(trustedDepositTokenAddress).safeApprove(address(uniswapRouterV2), amountAfterFee); uint _oldRewardTokenBalance = IERC20(trustedRewardTokenAddress).balanceOf(address(this)); uint _oldBaseTokenBalance = IERC20(trustedBaseTokenAddress).balanceOf(address(this)); uniswapRouterV2.removeLiquidity( trustedRewardTokenAddress, trustedBaseTokenAddress, amountAfterFee, /*_amountLiquidityMin_rewardToken*/ minAmounts[0], /*_amountLiquidityMin_baseToken*/minAmounts[1], address(this), _deadline ); uint _newRewardTokenBalance = IERC20(trustedRewardTokenAddress).balanceOf(address(this)); uint _newBaseTokenBalance = IERC20(trustedBaseTokenAddress).balanceOf(address(this)); uint _rewardTokenReceivedAfterRemovingLiquidity = _newRewardTokenBalance.sub(_oldRewardTokenBalance); uint _baseTokenReceivedAfterRemovingLiquidity = _newBaseTokenBalance.sub(_oldBaseTokenBalance); uint withdrawTokenReceived1 = doSwap(trustedRewardTokenAddress, withdrawAsToken, _rewardTokenReceivedAfterRemovingLiquidity, /*_amountOutMin_withdrawAsToken_rewardTokenReceived*/minAmounts[2], _deadline); uint withdrawTokenReceived2 = doSwap(trustedBaseTokenAddress, withdrawAsToken, _baseTokenReceivedAfterRemovingLiquidity, /*_amountOutMin_withdrawAsToken_baseTokenReceived*/minAmounts[3], _deadline); uint tokensReceived = withdrawTokenReceived1.add(withdrawTokenReceived2); return tokensReceived; } // claim function to claim pending rewards function claim(uint _amountOutMin_claimAsToken_dyp, uint _amountOutMin_attemptSwap, uint _deadline) public noContractsAllowed notDuringEmergency { updateAccount(msg.sender, _amountOutMin_claimAsToken_dyp, _amountOutMin_attemptSwap, _deadline); } function claimAs(address claimAsToken, uint _amountOutMin_claimAsToken_weth, uint _amountOutMin_claimAsToken_dyp, uint _amountOutMin_attemptSwap, uint _deadline) public noContractsAllowed notDuringEmergency { require(trustedClaimableTokens[claimAsToken], "cannot claim as this token!"); updateAccount(msg.sender, claimAsToken, _amountOutMin_claimAsToken_weth, _amountOutMin_claimAsToken_dyp, _amountOutMin_attemptSwap, _deadline); } // private function to distribute DYP rewards function distributeDivs(uint amount) private { require(amount > 0 && totalTokens > 0, "distributeDivs failed!"); totalDivPoints = totalDivPoints.add(amount.mul(pointMultiplier).div(totalTokens)); emit RewardsDisbursed(amount); } // private function to distribute WETH rewards function distributeDivsEth(uint amount) private { require(amount > 0 && totalTokens > 0, "distributeDivsEth failed!"); totalEthDivPoints = totalEthDivPoints.add(amount.mul(pointMultiplier).div(totalTokens)); emit EthRewardsDisbursed(amount); } // private function to allocate DYP to be disbursed calculated according to time passed function disburseTokens() private { uint amount = getPendingDisbursement(); if (contractBalance < amount) { amount = contractBalance; } if (amount == 0 || totalTokens == 0) return; tokensToBeSwapped = tokensToBeSwapped.add(amount); contractBalance = contractBalance.sub(amount); lastDisburseTime = now; } function attemptSwap(uint _amountOutMin_attemptSwap, uint _deadline) private { // do not attemptSwap if no one has staked if (totalTokens == 0) { return; } // Cannot execute swap so quickly if (now.sub(lastSwapExecutionTime) < swapAttemptPeriod) { return; } // force reserves to match balances uniswapV2Pair.sync(); uint _tokensToBeSwapped = tokensToBeSwapped.add(tokensToBeDisbursedOrBurnt); uint maxSwappableAmount = getMaxSwappableAmount(); // don't proceed if no liquidity if (maxSwappableAmount == 0) return; if (maxSwappableAmount < tokensToBeSwapped) { uint diff = tokensToBeSwapped.sub(maxSwappableAmount); _tokensToBeSwapped = tokensToBeSwapped.sub(diff); tokensToBeDisbursedOrBurnt = tokensToBeDisbursedOrBurnt.add(diff); tokensToBeSwapped = 0; } else if (maxSwappableAmount < _tokensToBeSwapped) { uint diff = _tokensToBeSwapped.sub(maxSwappableAmount); _tokensToBeSwapped = _tokensToBeSwapped.sub(diff); tokensToBeDisbursedOrBurnt = diff; tokensToBeSwapped = 0; } else { tokensToBeSwapped = 0; tokensToBeDisbursedOrBurnt = 0; } // don't execute 0 swap tokens if (_tokensToBeSwapped == 0) { return; } // cannot execute swap at insufficient balance if (IERC20(trustedRewardTokenAddress).balanceOf(address(this)) < _tokensToBeSwapped) { return; } IERC20(trustedRewardTokenAddress).safeApprove(address(uniswapRouterV2), 0); IERC20(trustedRewardTokenAddress).safeApprove(address(uniswapRouterV2), _tokensToBeSwapped); uint oldWethBalance = IERC20(uniswapRouterV2.WETH()).balanceOf(address(this)); uniswapRouterV2.swapExactTokensForTokens(_tokensToBeSwapped, _amountOutMin_attemptSwap, SWAP_PATH, address(this), _deadline); uint newWethBalance = IERC20(uniswapRouterV2.WETH()).balanceOf(address(this)); uint wethReceived = newWethBalance.sub(oldWethBalance); if (wethReceived > 0) { distributeDivsEth(wethReceived); } lastSwapExecutionTime = now; } // Owner is supposed to be a Governance Contract function disburseRewardTokens() public onlyOwner { require(now.sub(lastBurnOrTokenDistributeTime) > burnOrDisburseTokensPeriod, "Recently executed, Please wait!"); // force reserves to match balances uniswapV2Pair.sync(); uint maxSwappableAmount = getMaxSwappableAmount(); uint _tokensToBeDisbursed = tokensToBeDisbursedOrBurnt; uint _tokensToBeBurnt; if (maxSwappableAmount < _tokensToBeDisbursed) { _tokensToBeBurnt = _tokensToBeDisbursed.sub(maxSwappableAmount); _tokensToBeDisbursed = maxSwappableAmount; } distributeDivs(_tokensToBeDisbursed); if (_tokensToBeBurnt > 0) { IERC20(trustedRewardTokenAddress).safeTransfer(BURN_ADDRESS, _tokensToBeBurnt); } tokensToBeDisbursedOrBurnt = 0; lastBurnOrTokenDistributeTime = now; } // Owner is suposed to be a Governance Contract function burnRewardTokens() public onlyOwner { require(now.sub(lastBurnOrTokenDistributeTime) > burnOrDisburseTokensPeriod, "Recently executed, Please wait!"); IERC20(trustedRewardTokenAddress).safeTransfer(BURN_ADDRESS, tokensToBeDisbursedOrBurnt); tokensToBeDisbursedOrBurnt = 0; lastBurnOrTokenDistributeTime = now; } // get token amount which has a max price impact according to MAGIC_NUMBER for sells // !!IMPORTANT!! => Any functions using return value from this // MUST call `sync` on the pair before calling this function! function getMaxSwappableAmount() public view returns (uint) { uint tokensAvailable = IERC20(trustedRewardTokenAddress).balanceOf(trustedDepositTokenAddress); uint maxSwappableAmount = tokensAvailable.mul(MAGIC_NUMBER).div(1e18); return maxSwappableAmount; } // view function to calculate amount of DYP pending to be allocated since `lastDisburseTime` function getPendingDisbursement() public view returns (uint) { uint timeDiff; uint _now = now; uint _stakingEndTime = contractDeployTime.add(disburseDuration); if (_now > _stakingEndTime) { _now = _stakingEndTime; } if (lastDisburseTime >= _now) { timeDiff = 0; } else { timeDiff = _now.sub(lastDisburseTime); } uint pendingDisburse = disburseAmount .mul(disbursePercentX100) .mul(timeDiff) .div(disburseDuration) .div(10000); return pendingDisburse; } // view function to get depositors list function getDepositorsList(uint startIndex, uint endIndex) public view returns (address[] memory stakers, uint[] memory stakingTimestamps, uint[] memory lastClaimedTimeStamps, uint[] memory stakedTokens) { require (startIndex < endIndex); uint length = endIndex.sub(startIndex); address[] memory _stakers = new address[](length); uint[] memory _stakingTimestamps = new uint[](length); uint[] memory _lastClaimedTimeStamps = new uint[](length); uint[] memory _stakedTokens = new uint[](length); for (uint i = startIndex; i < endIndex; i = i.add(1)) { address staker = holders.at(i); uint listIndex = i.sub(startIndex); _stakers[listIndex] = staker; _stakingTimestamps[listIndex] = depositTime[staker]; _lastClaimedTimeStamps[listIndex] = lastClaimedTime[staker]; _stakedTokens[listIndex] = depositedTokens[staker]; } return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens); } // admin can claim any tokens left in the contract after it expires or during emergency function claimAnyToken(address token, address recipient, uint amount) external onlyOwner { require(recipient != address(0), "Invalid Recipient"); require(now > adminClaimableTime, "Contract not expired yet!"); if (token == address(0)) { address payable _recipient = payable(recipient); _recipient.transfer(amount); return; } IERC20(token).safeTransfer(recipient, amount); } }
do not attemptSwap if no one has staked Cannot execute swap so quickly don't execute 0 swap tokens cannot execute swap at insufficient balance
function attemptSwap(uint _amountOutMin_attemptSwap, uint _deadline) private { if (totalTokens == 0) { return; } if (now.sub(lastSwapExecutionTime) < swapAttemptPeriod) { return; } uint _tokensToBeSwapped = tokensToBeSwapped.add(tokensToBeDisbursedOrBurnt); uint maxSwappableAmount = getMaxSwappableAmount(); if (maxSwappableAmount < tokensToBeSwapped) { uint diff = tokensToBeSwapped.sub(maxSwappableAmount); _tokensToBeSwapped = tokensToBeSwapped.sub(diff); tokensToBeDisbursedOrBurnt = tokensToBeDisbursedOrBurnt.add(diff); tokensToBeSwapped = 0; uint diff = _tokensToBeSwapped.sub(maxSwappableAmount); _tokensToBeSwapped = _tokensToBeSwapped.sub(diff); tokensToBeDisbursedOrBurnt = diff; tokensToBeSwapped = 0; tokensToBeSwapped = 0; tokensToBeDisbursedOrBurnt = 0; } if (_tokensToBeSwapped == 0) { return; } if (IERC20(trustedRewardTokenAddress).balanceOf(address(this)) < _tokensToBeSwapped) { return; } IERC20(trustedRewardTokenAddress).safeApprove(address(uniswapRouterV2), 0); IERC20(trustedRewardTokenAddress).safeApprove(address(uniswapRouterV2), _tokensToBeSwapped); uint oldWethBalance = IERC20(uniswapRouterV2.WETH()).balanceOf(address(this)); uniswapRouterV2.swapExactTokensForTokens(_tokensToBeSwapped, _amountOutMin_attemptSwap, SWAP_PATH, address(this), _deadline); uint newWethBalance = IERC20(uniswapRouterV2.WETH()).balanceOf(address(this)); uint wethReceived = newWethBalance.sub(oldWethBalance); if (wethReceived > 0) { distributeDivsEth(wethReceived); } lastSwapExecutionTime = now; }
1,338,286
contract Entity {} contract AttributeList { // an Attribute is a single key->value pair, optionally with an address->value mapping struct Attribute { bytes32 value;// 32 bytes for now :/ bool linkable; mapping (address => bytes32) links; } function setAttribute(bytes32 key, bytes32 value, bool linkable) { Attribute a = attributes[key]; a.value = value; a.linkable = linkable; } function setLink(bytes32 key, bytes32 value) returns (bool) { Attribute a = attributes[key]; if(a.linkable) { a.links[msg.sender] = value; return true; } return false; } function removeAttribute(bytes32 key) { Attribute a = attributes[key]; delete a; } function removeLink(bytes32 key) { Attribute a = attributes[key]; a.links[msg.sender] = bytes32(0); } mapping (bytes32 => Attribute) attributes; } contract AddressGroup { function addMember(address a) { if(!isMember(a)) { members[a] = true; memberTotal += 1; } } function removeMember(address a) { if(isMember(a)) { members[a] = false; memberTotal -= 1; if(memberTotal==0) { suicide(a); } } } function isMember(address a) returns (bool) { return members[a]; } modifier onlyMember { if(isMember(msg.sender)) { _ } } mapping (address => bool) members; uint public memberTotal; } contract VotingGroup is AddressGroup { struct VoteItem { uint M; uint N; bytes data; uint created; uint maxBlocks; uint memberTotalSig; uint numVotes; mapping (address => bool) votes; } struct VotePolicy { bool isSet; uint M; // M-of-N or if N==0: M; uint N; uint maxBlocks; } // needsVote allows for enabling a vote-requirement for a specific function. // _m, _n, and _max configure the default voting policy for the function. // _m - the required numerator of votes required or, if n == 0, the number of absolute votes required // _n - the denominator of votes required. Set to 0 to trigger absolute vote counting rather than percent of voters counting // _max - the maximum number of blocks before a vote is allowed to be deleted. Set to 0 for no limit. modifier needsVote(uint _m, uint _n, uint _max) { if(!isMember(msg.sender)) { return; } VotePolicy vp = policies[msg.sig]; // if a vote policy isn't in place, init the policy with hardcoded vals if(!vp.isSet) { vp.M = _m; vp.N = _n; vp.maxBlocks = _max; vp.isSet = true; } // TODO, handle repeated exact functions properly VoteItem vi = items[sha3(msg.data,memberTotalSig)]; // if vote item doesn't exist, create it if(vi.created == 0) { vi.M = vp.M; vi.N = vp.N; vi.maxBlocks = vi.maxBlocks; vi.data = msg.data; vi.numVotes = 0; vi.created = block.number; } // if sender hasn't voted, record vote if(!vi.votes[msg.sender]) { vi.votes[msg.sender] = true; vi.numVotes += 1; } // check for vote 'completion' if((vi.N == 3 && vi.numVotes >= vi.M) || ((memberTotal * vi.M) < (vi.numVotes * vi.N))) { delete vi; _ } } // remove old expired vote items function removeItem(bytes32 i) onlyMember { VoteItem vi = items[i]; if((vi.maxBlocks != 0 && (block.number - vi.created) > vi.maxBlocks) || vi.memberTotalSig != memberTotalSig) { delete vi; } } // change vote policy for a function, identified by 4-byte signature function changePolicy(bytes4 sig, uint _m, uint _n, uint _max) needsVote(4,5,10) { VotePolicy p = policies[sig]; p.M = _m; p.N = _n; p.maxBlocks = _max; } // items stores all currently-being-voted-on items mapping (bytes32 => VoteItem) items; // policies stores all vote policies, set per function mapping (bytes4 => VotePolicy) policies; // memberTotalSig increments any time there is a change in membership. // This is used to determine if a vote item is stale by tracking membership changes. uint memberTotalSig; // update memberTotalSig on membership change // increment memberTotalSig on any change in membership function addMember(address a) { uint t = memberTotal; super.addMember(a); if(t != memberTotal) { memberTotalSig += 1; } } function removeMember(address a) { uint t = memberTotal; super.removeMember(a); if(t != memberTotal) { memberTotalSig += 1; } } } contract Identity is Entity, AttributeList, VotingGroup { // entity // TODO: tailor entity method // attribute list access function setAttribute(bytes32 key, bytes32 value, bool linkable) needsVote(2,3,10) { super.setAttribute(key, value, linkable); } function removeAttribute(bytes32 key) needsVote(2,3,10) { super.removeAttribute(key); } // group membership function addMember(address a) needsVote(2,3,10) { super.addMember(a); } function removeMember(address a) needsVote(2,3,10) { super.removeMember(a); } }
update memberTotalSig on membership change increment memberTotalSig on any change in membership
function addMember(address a) { uint t = memberTotal; super.addMember(a); if(t != memberTotal) { memberTotalSig += 1; } }
12,795,141
./partial_match/1/0xd904Fa10e6e7106A1D46B7231C5d2379fA7D5d14/sources/TrustedIssuersRegistry.sol
See {ITrustedIssuersRegistry-getTrustedIssuerClaimTopics}./
function getTrustedIssuerClaimTopics(IClaimIssuer _trustedIssuer) external override view returns (uint[] memory) { require(trustedIssuerClaimTopics[address(_trustedIssuer)].length != 0, "trusted Issuer doesn't exist"); return trustedIssuerClaimTopics[address(_trustedIssuer)]; }
3,893,588
pragma solidity ^0.4.11; contract ChronoBankPlatform { mapping(bytes32 => address) public proxies; function symbols(uint _idx) public constant returns (bytes32); function symbolsCount() public constant returns (uint); function name(bytes32 _symbol) returns(string); function setProxy(address _address, bytes32 _symbol) returns(uint errorCode); function isCreated(bytes32 _symbol) constant returns(bool); function isOwner(address _owner, bytes32 _symbol) returns(bool); function owner(bytes32 _symbol) constant returns(address); function totalSupply(bytes32 _symbol) returns(uint); function balanceOf(address _holder, bytes32 _symbol) returns(uint); function allowance(address _from, address _spender, bytes32 _symbol) returns(uint); function baseUnit(bytes32 _symbol) returns(uint8); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, address _account) returns(uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) returns(uint errorCode); function revokeAsset(bytes32 _symbol, uint _value) returns(uint errorCode); function isReissuable(bytes32 _symbol) returns(bool); function changeOwnership(bytes32 _symbol, address _newOwner) returns(uint errorCode); } contract ChronoBankAsset { function __transferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool); function __approve(address _spender, uint _value, address _sender) returns(bool); function __process(bytes _data, address _sender) payable { revert(); } } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } /** * @title ChronoBank Asset Proxy. * * Proxy implements ERC20 interface and acts as a gateway to a single platform asset. * Proxy adds symbol and caller(sender) when forwarding requests to platform. * Every request that is made by caller first sent to the specific asset implementation * contract, which then calls back to be forwarded onto platform. * * Calls flow: Caller -> * Proxy.func(...) -> * Asset.__func(..., Caller.address) -> * Proxy.__func(..., Caller.address) -> * Platform.proxyFunc(..., symbol, Caller.address) * * Asset implementation contract is mutable, but each user have an option to stick with * old implementation, through explicit decision made in timely manner, if he doesn&#39;t agree * with new rules. * Each user have a possibility to upgrade to latest asset contract implementation, without the * possibility to rollback. * * Note: all the non constant functions return false instead of throwing in case if state change * didn&#39;t happen yet. */ contract ChronoBankAssetProxy is ERC20 { // Supports ChronoBankPlatform ability to return error codes from methods uint constant OK = 1; // Assigned platform, immutable. ChronoBankPlatform public chronoBankPlatform; // Assigned symbol, immutable. bytes32 public smbl; // Assigned name, immutable. string public name; string public symbol; /** * Sets platform address, assigns symbol and name. * * Can be set only once. * * @param _chronoBankPlatform platform contract address. * @param _symbol assigned symbol. * @param _name assigned name. * * @return success. */ function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) returns(bool) { if (address(chronoBankPlatform) != 0x0) { return false; } chronoBankPlatform = _chronoBankPlatform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } function stringToBytes32(string memory source) returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /** * Only platform is allowed to call. */ modifier onlyChronoBankPlatform() { if (msg.sender == address(chronoBankPlatform)) { _; } } /** * Only current asset owner is allowed to call. */ modifier onlyAssetOwner() { if (chronoBankPlatform.isOwner(msg.sender, smbl)) { _; } } /** * Returns asset implementation contract for current caller. * * @return asset implementation contract. */ function _getAsset() internal returns(ChronoBankAsset) { return ChronoBankAsset(getVersionFor(msg.sender)); } /** * Returns asset total supply. * * @return asset total supply. */ function totalSupply() constant returns(uint) { return chronoBankPlatform.totalSupply(smbl); } /** * Returns asset balance for a particular holder. * * @param _owner holder address. * * @return holder balance. */ function balanceOf(address _owner) constant returns(uint) { return chronoBankPlatform.balanceOf(_owner, smbl); } /** * Returns asset allowance from one holder to another. * * @param _from holder that allowed spending. * @param _spender holder that is allowed to spend. * * @return holder to spender allowance. */ function allowance(address _from, address _spender) constant returns(uint) { return chronoBankPlatform.allowance(_from, _spender, smbl); } /** * Returns asset decimals. * * @return asset decimals. */ function decimals() constant returns(uint8) { return chronoBankPlatform.baseUnit(smbl); } /** * Transfers asset balance from the caller to specified receiver. * * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transfer(address _to, uint _value) returns(bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } else { return false; } } /** * Transfers asset balance from the caller to specified receiver adding specified comment. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform&#39;s Transfer event. * * @return success. */ function transferWithReference(address _to, uint _value, string _reference) returns(bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } else { return false; } } /** * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @return success. */ function _transferWithReference(address _to, uint _value, string _reference) internal returns(bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } /** * Performs transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform&#39;s Transfer event. * @param _sender initial caller. * * @return success. */ function __transferWithReference(address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) { return chronoBankPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /** * Prforms allowance transfer of asset balance between holders. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transferFrom(address _from, address _to, uint _value) returns(bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } else { return false; } } /** * Performs allowance transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform&#39;s Transfer event. * @param _sender initial caller. * * @return success. */ function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyAccess(_sender) returns(bool) { return chronoBankPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /** * Sets asset spending allowance for a specified spender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * * @return success. */ function approve(address _spender, uint _value) returns(bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } else { return false; } } /** * Performs allowance setting call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * @param _sender initial caller. * * @return success. */ function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) returns(bool) { return chronoBankPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /** * Emits ERC20 Transfer event on this contract. * * Can only be, and, called by assigned platform when asset transfer happens. */ function emitTransfer(address _from, address _to, uint _value) onlyChronoBankPlatform() { Transfer(_from, _to, _value); } /** * Emits ERC20 Approval event on this contract. * * Can only be, and, called by assigned platform when asset allowance set happens. */ function emitApprove(address _from, address _spender, uint _value) onlyChronoBankPlatform() { Approval(_from, _spender, _value); } /** * Resolves asset implementation contract for the caller and forwards there transaction data, * along with the value. This allows for proxy interface growth. */ function () payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /** * Indicates an upgrade freeze-time start, and the next asset implementation contract. */ event UpgradeProposal(address newVersion); // Current asset implementation contract address. address latestVersion; // Proposed next asset implementation contract address. address pendingVersion; // Upgrade freeze-time start. uint pendingVersionTimestamp; // Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; // Asset implementation contract address that user decided to stick with. // 0x0 means that user uses latest version. mapping(address => address) userOptOutVersion; /** * Only asset implementation contract assigned to sender is allowed to call. */ modifier onlyAccess(address _sender) { if (getVersionFor(_sender) == msg.sender) { _; } } /** * Returns asset implementation contract address assigned to sender. * * @param _sender sender address. * * @return asset implementation contract address. */ function getVersionFor(address _sender) constant returns(address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /** * Returns current asset implementation contract address. * * @return asset implementation contract address. */ function getLatestVersion() constant returns(address) { return latestVersion; } /** * Returns proposed next asset implementation contract address. * * @return asset implementation contract address. */ function getPendingVersion() constant returns(address) { return pendingVersion; } /** * Returns upgrade freeze-time start. * * @return freeze-time start. */ function getPendingVersionTimestamp() constant returns(uint) { return pendingVersionTimestamp; } /** * Propose next asset implementation contract address. * * Can only be called by current asset owner. * * Note: freeze-time should not be applied for the initial setup. * * @param _newVersion asset implementation contract address. * * @return success. */ function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don&#39;t apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; UpgradeProposal(_newVersion); return true; } /** * Cancel the pending upgrade process. * * Can only be called by current asset owner. * * @return success. */ function purgeUpgrade() onlyAssetOwner() returns(bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Finalize an upgrade process setting new asset implementation contract address. * * Can only be called after an upgrade freeze-time. * * @return success. */ function commitUpgrade() returns(bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Disagree with proposed upgrade, and stick with current asset implementation * until further explicit agreement to upgrade. * * @return success. */ function optOut() returns(bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; return true; } /** * Implicitly agree to upgrade to current and future asset implementation upgrades, * until further explicit disagreement. * * @return success. */ function optIn() returns(bool) { delete userOptOutVersion[msg.sender]; return true; } }
Returns proposed next asset implementation contract address. return asset implementation contract address./
function getPendingVersion() constant returns(address) { return pendingVersion; }
15,415,267
/** *Submitted for verification at Etherscan.io on 2021-03-12 */ pragma solidity 0.6.6; // File: @openzeppelin/contracts/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/oracle/LatestPriceOracleInterface.sol pragma solidity 0.6.6; /** * @dev Interface of the price oracle. */ interface LatestPriceOracleInterface { /** * @dev Returns `true`if oracle is working. */ function isWorking() external returns (bool); /** * @dev Returns the last updated price. Decimals is 8. **/ function latestPrice() external returns (uint256); /** * @dev Returns the timestamp of the last updated price. */ function latestTimestamp() external returns (uint256); } // File: contracts/oracle/PriceOracleInterface.sol pragma solidity 0.6.6; /** * @dev Interface of the price oracle. */ interface PriceOracleInterface is LatestPriceOracleInterface { /** * @dev Returns the latest id. The id start from 1 and increments by 1. */ function latestId() external returns (uint256); /** * @dev Returns the historical price specified by `id`. Decimals is 8. */ function getPrice(uint256 id) external returns (uint256); /** * @dev Returns the timestamp of historical price specified by `id`. */ function getTimestamp(uint256 id) external returns (uint256); } // File: contracts/oracle/OracleInterface.sol pragma solidity 0.6.6; // Oracle referenced by OracleProxy must implement this interface. interface OracleInterface is PriceOracleInterface { function getVolatility() external returns (uint256); function lastCalculatedVolatility() external view returns (uint256); } // File: contracts/oracle/VolatilityOracleInterface.sol pragma solidity 0.6.6; interface VolatilityOracleInterface { function getVolatility(uint64 untilMaturity) external view returns (uint64 volatilityE8); } // File: contracts/util/TransferETHInterface.sol pragma solidity 0.6.6; interface TransferETHInterface { receive() external payable; event LogTransferETH(address indexed from, address indexed to, uint256 value); } // File: contracts/bondToken/BondTokenInterface.sol pragma solidity 0.6.6; interface BondTokenInterface is IERC20 { event LogExpire(uint128 rateNumerator, uint128 rateDenominator, bool firstTime); function mint(address account, uint256 amount) external returns (bool success); function expire(uint128 rateNumerator, uint128 rateDenominator) external returns (bool firstTime); function simpleBurn(address account, uint256 amount) external returns (bool success); function burn(uint256 amount) external returns (bool success); function burnAll() external returns (uint256 amount); function getRate() external view returns (uint128 rateNumerator, uint128 rateDenominator); } // File: contracts/bondMaker/BondMakerInterface.sol pragma solidity 0.6.6; interface BondMakerInterface { event LogNewBond( bytes32 indexed bondID, address indexed bondTokenAddress, uint256 indexed maturity, bytes32 fnMapID ); event LogNewBondGroup( uint256 indexed bondGroupID, uint256 indexed maturity, uint64 indexed sbtStrikePrice, bytes32[] bondIDs ); event LogIssueNewBonds( uint256 indexed bondGroupID, address indexed issuer, uint256 amount ); event LogReverseBondGroupToCollateral( uint256 indexed bondGroupID, address indexed owner, uint256 amount ); event LogExchangeEquivalentBonds( address indexed owner, uint256 indexed inputBondGroupID, uint256 indexed outputBondGroupID, uint256 amount ); event LogLiquidateBond( bytes32 indexed bondID, uint128 rateNumerator, uint128 rateDenominator ); function registerNewBond(uint256 maturity, bytes calldata fnMap) external returns ( bytes32 bondID, address bondTokenAddress, bytes32 fnMapID ); function registerNewBondGroup( bytes32[] calldata bondIDList, uint256 maturity ) external returns (uint256 bondGroupID); function reverseBondGroupToCollateral(uint256 bondGroupID, uint256 amount) external returns (bool success); function exchangeEquivalentBonds( uint256 inputBondGroupID, uint256 outputBondGroupID, uint256 amount, bytes32[] calldata exceptionBonds ) external returns (bool); function liquidateBond(uint256 bondGroupID, uint256 oracleHintID) external returns (uint256 totalPayment); function collateralAddress() external view returns (address); function oracleAddress() external view returns (PriceOracleInterface); function feeTaker() external view returns (address); function decimalsOfBond() external view returns (uint8); function decimalsOfOraclePrice() external view returns (uint8); function maturityScale() external view returns (uint256); function nextBondGroupID() external view returns (uint256); function getBond(bytes32 bondID) external view returns ( address bondAddress, uint256 maturity, uint64 solidStrikePrice, bytes32 fnMapID ); function getFnMap(bytes32 fnMapID) external view returns (bytes memory fnMap); function getBondGroup(uint256 bondGroupID) external view returns (bytes32[] memory bondIDs, uint256 maturity); function generateFnMapID(bytes calldata fnMap) external view returns (bytes32 fnMapID); function generateBondID(uint256 maturity, bytes calldata fnMap) external view returns (bytes32 bondID); } // File: contracts/bondPricer/Enums.sol pragma solidity 0.6.6; /** Pure SBT: ___________ / / / / LBT Shape: / / / / ______/ SBT Shape: ______ / / _______/ Triangle: /\ / \ / \ _______/ \________ */ enum BondType {NONE, PURE_SBT, SBT_SHAPE, LBT_SHAPE, TRIANGLE} // File: contracts/bondPricer/BondPricerInterface.sol pragma solidity 0.6.6; interface BondPricerInterface { /** * @notice Calculate bond price and leverage by black-scholes formula. * @param bondType type of target bond. * @param points coodinates of polyline which is needed for price calculation * @param spotPrice is a oracle price. * @param volatilityE8 is a oracle volatility. * @param untilMaturity Remaining period of target bond in second **/ function calcPriceAndLeverage( BondType bondType, uint256[] calldata points, int256 spotPrice, int256 volatilityE8, int256 untilMaturity ) external view returns (uint256 price, uint256 leverageE8); } // File: @openzeppelin/contracts/math/SignedSafeMath.sol /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // File: @openzeppelin/contracts/utils/SafeCast.sol /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/math/UseSafeMath.sol pragma solidity 0.6.6; /** * @notice ((a - 1) / b) + 1 = (a + b -1) / b * for example a.add(10**18 -1).div(10**18) = a.sub(1).div(10**18) + 1 */ library SafeMathDivRoundUp { using SafeMath for uint256; function divRoundUp( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0) { return 0; } require(b > 0, errorMessage); return ((a - 1) / b) + 1; } function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return divRoundUp(a, b, "SafeMathDivRoundUp: modulo by zero"); } } /** * @title UseSafeMath * @dev One can use SafeMath for not only uint256 but also uin64 or uint16, * and also can use SafeCast for uint256. * For example: * uint64 a = 1; * uint64 b = 2; * a = a.add(b).toUint64() // `a` become 3 as uint64 * In addition, one can use SignedSafeMath and SafeCast.toUint256(int256) for int256. * In the case of the operation to the uint64 value, one needs to cast the value into int256 in * advance to use `sub` as SignedSafeMath.sub not SafeMath.sub. * For example: * int256 a = 1; * uint64 b = 2; * int256 c = 3; * a = a.add(int256(b).sub(c)); // `a` becomes 0 as int256 * b = a.toUint256().toUint64(); // `b` becomes 0 as uint64 */ abstract contract UseSafeMath { using SafeMath for uint256; using SafeMathDivRoundUp for uint256; using SafeMath for uint64; using SafeMathDivRoundUp for uint64; using SafeMath for uint16; using SignedSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; } // File: contracts/util/Polyline.sol pragma solidity 0.6.6; contract Polyline is UseSafeMath { struct Point { uint64 x; // Value of the x-axis of the x-y plane uint64 y; // Value of the y-axis of the x-y plane } struct LineSegment { Point left; // The left end of the line definition range Point right; // The right end of the line definition range } /** * @notice Return the value of y corresponding to x on the given line. line in the form of * a rational number (numerator / denominator). * If you treat a line as a line segment instead of a line, you should run * includesDomain(line, x) to check whether x is included in the line's domain or not. * @dev To guarantee accuracy, the bit length of the denominator must be greater than or equal * to the bit length of x, and the bit length of the numerator must be greater than or equal * to the sum of the bit lengths of x and y. */ function _mapXtoY(LineSegment memory line, uint64 x) internal pure returns (uint128 numerator, uint64 denominator) { int256 x1 = int256(line.left.x); int256 y1 = int256(line.left.y); int256 x2 = int256(line.right.x); int256 y2 = int256(line.right.y); require(x2 > x1, "must be left.x < right.x"); denominator = uint64(x2 - x1); // Calculate y = ((x2 - x) * y1 + (x - x1) * y2) / (x2 - x1) // in the form of a fraction (numerator / denominator). int256 n = (x - x1) * y2 + (x2 - x) * y1; require(n >= 0, "underflow n"); require(n < 2**128, "system error: overflow n"); numerator = uint128(n); } /** * @notice Checking that a line segment is a valid format. */ function assertLineSegment(LineSegment memory segment) internal pure { uint64 x1 = segment.left.x; uint64 x2 = segment.right.x; require(x1 < x2, "must be left.x < right.x"); } /** * @notice Checking that a polyline is a valid format. */ function assertPolyline(LineSegment[] memory polyline) internal pure { uint256 numOfSegment = polyline.length; require(numOfSegment != 0, "polyline must not be empty array"); LineSegment memory leftSegment = polyline[0]; // mutable int256 gradientNumerator = int256(leftSegment.right.y) - int256(leftSegment.left.y); // mutable int256 gradientDenominator = int256(leftSegment.right.x) - int256(leftSegment.left.x); // mutable // The beginning of the first line segment's domain is 0. require( leftSegment.left.x == uint64(0), "the x coordinate of left end of the first segment must be 0" ); // The value of y when x is 0 is 0. require( leftSegment.left.y == uint64(0), "the y coordinate of left end of the first segment must be 0" ); // Making sure that the first line segment is a correct format. assertLineSegment(leftSegment); // The end of the domain of a segment and the beginning of the domain of the adjacent // segment must coincide. LineSegment memory rightSegment; // mutable for (uint256 i = 1; i < numOfSegment; i++) { rightSegment = polyline[i]; // Make sure that the i-th line segment is a correct format. assertLineSegment(rightSegment); // Checking that the x-coordinates are same. require( leftSegment.right.x == rightSegment.left.x, "given polyline has an undefined domain." ); // Checking that the y-coordinates are same. require( leftSegment.right.y == rightSegment.left.y, "given polyline is not a continuous function" ); int256 nextGradientNumerator = int256(rightSegment.right.y) - int256(rightSegment.left.y); int256 nextGradientDenominator = int256(rightSegment.right.x) - int256(rightSegment.left.x); require( nextGradientNumerator * gradientDenominator != nextGradientDenominator * gradientNumerator, "the sequential segments must not have the same gradient" ); leftSegment = rightSegment; gradientNumerator = nextGradientNumerator; gradientDenominator = nextGradientDenominator; } // rightSegment is lastSegment // About the last line segment. require( gradientNumerator >= 0 && gradientNumerator <= gradientDenominator, "the gradient of last line segment must be non-negative, and equal to or less than 1" ); } /** * @notice zip a LineSegment structure to uint256 * @return zip uint256( 0 ... 0 | x1 | y1 | x2 | y2 ) */ function zipLineSegment(LineSegment memory segment) internal pure returns (uint256 zip) { uint256 x1U256 = uint256(segment.left.x) << (64 + 64 + 64); // uint64 uint256 y1U256 = uint256(segment.left.y) << (64 + 64); // uint64 uint256 x2U256 = uint256(segment.right.x) << 64; // uint64 uint256 y2U256 = uint256(segment.right.y); // uint64 zip = x1U256 | y1U256 | x2U256 | y2U256; } /** * @notice unzip uint256 to a LineSegment structure */ function unzipLineSegment(uint256 zip) internal pure returns (LineSegment memory) { uint64 x1 = uint64(zip >> (64 + 64 + 64)); uint64 y1 = uint64(zip >> (64 + 64)); uint64 x2 = uint64(zip >> 64); uint64 y2 = uint64(zip); return LineSegment({ left: Point({x: x1, y: y1}), right: Point({x: x2, y: y2}) }); } /** * @notice unzip the fnMap to uint256[]. */ function decodePolyline(bytes memory fnMap) internal pure returns (uint256[] memory) { return abi.decode(fnMap, (uint256[])); } } // File: contracts/bondPricer/DetectBondShape.sol pragma solidity 0.6.6; contract DetectBondShape is Polyline { /** * @notice Detect bond type by polyline of bond. * @param bondID bondID of target bond token * @param submittedType if this parameter is BondType.NONE, this function checks up all bond types. Otherwise this function checks up only one bond type. * @param success whether bond detection succeeded or notice * @param points coodinates of polyline which is needed for price calculation **/ function getBondTypeByID( BondMakerInterface bondMaker, bytes32 bondID, BondType submittedType ) public view returns ( bool success, BondType, uint256[] memory points ) { (, , , bytes32 fnMapID) = bondMaker.getBond(bondID); bytes memory fnMap = bondMaker.getFnMap(fnMapID); return _getBondType(fnMap, submittedType); } /** * @notice Detect bond type by polyline of bond. * @param fnMap Function mapping of target bond token * @param submittedType If this parameter is BondType.NONE, this function checks up all bond types. Otherwise this function checks up only one bond type. * @param success Whether bond detection succeeded or not * @param points Coodinates of polyline which are needed for price calculation **/ function getBondType(bytes calldata fnMap, BondType submittedType) external pure returns ( bool success, BondType, uint256[] memory points ) { uint256[] memory polyline = decodePolyline(fnMap); LineSegment[] memory segments = new LineSegment[](polyline.length); for (uint256 i = 0; i < polyline.length; i++) { segments[i] = unzipLineSegment(polyline[i]); } assertPolyline(segments); return _getBondType(fnMap, submittedType); } function _getBondType(bytes memory fnMap, BondType submittedType) internal pure returns ( bool success, BondType, uint256[] memory points ) { if (submittedType == BondType.NONE) { (success, points) = _isSBT(fnMap); if (success) { return (success, BondType.PURE_SBT, points); } (success, points) = _isSBTShape(fnMap); if (success) { return (success, BondType.SBT_SHAPE, points); } (success, points) = _isLBTShape(fnMap); if (success) { return (success, BondType.LBT_SHAPE, points); } (success, points) = _isTriangle(fnMap); if (success) { return (success, BondType.TRIANGLE, points); } return (false, BondType.NONE, points); } else if (submittedType == BondType.PURE_SBT) { (success, points) = _isSBT(fnMap); if (success) { return (success, BondType.PURE_SBT, points); } } else if (submittedType == BondType.SBT_SHAPE) { (success, points) = _isSBTShape(fnMap); if (success) { return (success, BondType.SBT_SHAPE, points); } } else if (submittedType == BondType.LBT_SHAPE) { (success, points) = _isLBTShape(fnMap); if (success) { return (success, BondType.LBT_SHAPE, points); } } else if (submittedType == BondType.TRIANGLE) { (success, points) = _isTriangle(fnMap); if (success) { return (success, BondType.TRIANGLE, points); } } return (false, BondType.NONE, points); } function _isLBTShape(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 2) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); if ( secondLine.left.x != 0 && secondLine.left.y == 0 && secondLine.right.x > secondLine.left.x && secondLine.right.y != 0 ) { uint256[] memory _lines = new uint256[](3); _lines[0] = secondLine.left.x; _lines[1] = secondLine.right.x; _lines[2] = secondLine.right.y; return (true, _lines); } return (false, points); } function _isTriangle(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 4) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); LineSegment memory thirdLine = unzipLineSegment(zippedLines[2]); LineSegment memory forthLine = unzipLineSegment(zippedLines[3]); if ( secondLine.left.x != 0 && secondLine.left.y == 0 && secondLine.right.x > secondLine.left.x && secondLine.right.y != 0 && thirdLine.right.x > secondLine.right.x && thirdLine.right.y == 0 && forthLine.right.x > thirdLine.right.x && forthLine.right.y == 0 ) { uint256[] memory _lines = new uint256[](4); _lines[0] = secondLine.left.x; _lines[1] = secondLine.right.x; _lines[2] = secondLine.right.y; _lines[3] = thirdLine.right.x; return (true, _lines); } return (false, points); } function _isSBTShape(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 3) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); LineSegment memory thirdLine = unzipLineSegment(zippedLines[2]); if ( secondLine.left.x != 0 && secondLine.left.y == 0 && secondLine.right.x > secondLine.left.x && secondLine.right.y != 0 && thirdLine.right.x > secondLine.right.x && thirdLine.right.y == secondLine.right.y ) { uint256[] memory _lines = new uint256[](3); _lines[0] = secondLine.left.x; _lines[1] = secondLine.right.x; _lines[2] = secondLine.right.y; return (true, _lines); } return (false, points); } function _isSBT(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 2) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); if ( secondLine.left.x != 0 && secondLine.left.y == secondLine.left.x && secondLine.right.x > secondLine.left.x && secondLine.right.y == secondLine.left.y ) { uint256[] memory _lines = new uint256[](1); _lines[0] = secondLine.left.x; return (true, _lines); } return (false, points); } } // File: contracts/util/Time.sol pragma solidity 0.6.6; abstract contract Time { function _getBlockTimestampSec() internal view returns (uint256 unixtimesec) { unixtimesec = block.timestamp; // solhint-disable-line not-rely-on-time } } // File: contracts/generalizedDotc/BondExchange.sol pragma solidity 0.6.6; abstract contract BondExchange is UseSafeMath, Time { uint256 internal constant MIN_EXCHANGE_RATE_E8 = 0.000001 * 10**8; uint256 internal constant MAX_EXCHANGE_RATE_E8 = 1000000 * 10**8; int256 internal constant MAX_SPREAD_E8 = 10**8; // 100% /** * @dev the sum of decimalsOfBond of the bondMaker. * This value is constant by the restriction of `_assertBondMakerDecimals`. */ uint8 internal constant DECIMALS_OF_BOND = 8; /** * @dev the sum of decimalsOfOraclePrice of the bondMaker. * This value is constant by the restriction of `_assertBondMakerDecimals`. */ uint8 internal constant DECIMALS_OF_ORACLE_PRICE = 8; BondMakerInterface internal immutable _bondMakerContract; PriceOracleInterface internal immutable _priceOracleContract; VolatilityOracleInterface internal immutable _volatilityOracleContract; LatestPriceOracleInterface internal immutable _volumeCalculator; DetectBondShape internal immutable _bondShapeDetector; /** * @param bondMakerAddress is a bond maker contract. * @param volumeCalculatorAddress is a contract to convert the unit of a strike price to USD. */ constructor( BondMakerInterface bondMakerAddress, VolatilityOracleInterface volatilityOracleAddress, LatestPriceOracleInterface volumeCalculatorAddress, DetectBondShape bondShapeDetector ) public { _assertBondMakerDecimals(bondMakerAddress); _bondMakerContract = bondMakerAddress; _priceOracleContract = bondMakerAddress.oracleAddress(); _volatilityOracleContract = VolatilityOracleInterface( volatilityOracleAddress ); _volumeCalculator = volumeCalculatorAddress; _bondShapeDetector = bondShapeDetector; } function bondMakerAddress() external view returns (BondMakerInterface) { return _bondMakerContract; } function volumeCalculatorAddress() external view returns (LatestPriceOracleInterface) { return _volumeCalculator; } /** * @dev Get the latest price (USD) and historical volatility using oracle. * If the oracle is not working, `latestPrice` reverts. * @return priceE8 (10^-8 USD) */ function _getLatestPrice(LatestPriceOracleInterface oracle) internal returns (uint256 priceE8) { return oracle.latestPrice(); } /** * @dev Get the implied volatility using oracle. * @return volatilityE8 (10^-8) */ function _getVolatility( VolatilityOracleInterface oracle, uint64 untilMaturity ) internal view returns (uint256 volatilityE8) { return oracle.getVolatility(untilMaturity); } /** * @dev Returns bond tokenaddress, maturity, */ function _getBond(BondMakerInterface bondMaker, bytes32 bondID) internal view returns ( ERC20 bondToken, uint256 maturity, uint256 sbtStrikePrice, bytes32 fnMapID ) { address bondTokenAddress; (bondTokenAddress, maturity, sbtStrikePrice, fnMapID) = bondMaker .getBond(bondID); // Revert if `bondTokenAddress` is zero. bondToken = ERC20(bondTokenAddress); } /** * @dev Removes a decimal gap from the first argument. */ function _applyDecimalGap( uint256 baseAmount, uint8 decimalsOfBase, uint8 decimalsOfQuote ) internal pure returns (uint256 quoteAmount) { uint256 n; uint256 d; if (decimalsOfBase > decimalsOfQuote) { d = decimalsOfBase - decimalsOfQuote; } else if (decimalsOfBase < decimalsOfQuote) { n = decimalsOfQuote - decimalsOfBase; } // The consequent multiplication would overflow under extreme and non-blocking circumstances. require(n < 19 && d < 19, "decimal gap needs to be lower than 19"); return baseAmount.mul(10**n).div(10**d); } function _calcBondPriceAndSpread( BondPricerInterface bondPricer, bytes32 bondID, int16 feeBaseE4 ) internal returns (uint256 bondPriceE8, int256 spreadE8) { (, uint256 maturity, , ) = _getBond(_bondMakerContract, bondID); ( bool isKnownBondType, BondType bondType, uint256[] memory points ) = _bondShapeDetector.getBondTypeByID( _bondMakerContract, bondID, BondType.NONE ); require(isKnownBondType, "cannot calculate the price of this bond"); uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); uint256 oraclePriceE8 = _getLatestPrice(_priceOracleContract); uint256 oracleVolatilityE8 = _getVolatility( _volatilityOracleContract, untilMaturity.toUint64() ); uint256 leverageE8; (bondPriceE8, leverageE8) = bondPricer.calcPriceAndLeverage( bondType, points, oraclePriceE8.toInt256(), oracleVolatilityE8.toInt256(), untilMaturity.toInt256() ); spreadE8 = _calcSpread(oracleVolatilityE8, leverageE8, feeBaseE4); } function _calcSpread( uint256 oracleVolatilityE8, uint256 leverageE8, int16 feeBaseE4 ) internal pure returns (int256 spreadE8) { uint256 volE8 = oracleVolatilityE8 < 10**8 ? 10**8 : oracleVolatilityE8 > 2 * 10**8 ? 2 * 10**8 : oracleVolatilityE8; uint256 volTimesLevE16 = volE8 * leverageE8; // assert(volTimesLevE16 < 200 * 10**16); spreadE8 = (feeBaseE4 * ( feeBaseE4 < 0 || volTimesLevE16 < 10**16 ? 10**16 : volTimesLevE16 ) .toInt256()) / 10**12; spreadE8 = spreadE8 > MAX_SPREAD_E8 ? MAX_SPREAD_E8 : spreadE8; } /** * @dev Calculate the exchange volume on the USD basis. */ function _calcUsdPrice(uint256 amount) internal returns (uint256) { return amount.mul(_getLatestPrice(_volumeCalculator)) / 10**8; } /** * @dev Restirct the bond maker. */ function _assertBondMakerDecimals(BondMakerInterface bondMaker) internal view { require( bondMaker.decimalsOfOraclePrice() == DECIMALS_OF_ORACLE_PRICE, "the decimals of oracle price must be 8" ); require( bondMaker.decimalsOfBond() == DECIMALS_OF_BOND, "the decimals of bond token must be 8" ); } function _assertExpectedPriceRange( uint256 actualAmount, uint256 expectedAmount, uint256 range ) internal pure { if (expectedAmount != 0) { require( actualAmount.mul(1000 + range).div(1000) >= expectedAmount, "out of expected price range" ); } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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/generalizedDotc/BondVsErc20Exchange.sol pragma solidity 0.6.6; abstract contract BondVsErc20Exchange is BondExchange { using SafeERC20 for ERC20; struct VsErc20Pool { address seller; ERC20 swapPairToken; LatestPriceOracleInterface swapPairOracle; BondPricerInterface bondPricer; int16 feeBaseE4; bool isBondSale; } mapping(bytes32 => VsErc20Pool) internal _vsErc20Pool; event LogCreateErc20ToBondPool( bytes32 indexed poolID, address indexed seller, address indexed swapPairAddress ); event LogCreateBondToErc20Pool( bytes32 indexed poolID, address indexed seller, address indexed swapPairAddress ); event LogUpdateVsErc20Pool( bytes32 indexed poolID, address swapPairOracleAddress, address bondPricerAddress, int16 feeBase // decimal: 4 ); event LogDeleteVsErc20Pool(bytes32 indexed poolID); event LogExchangeErc20ToBond( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: ERC20.decimals() uint256 volume // USD, decimal: 8 ); event LogExchangeBondToErc20( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: ERC20.decimals() uint256 volume // USD, decimal: 8 ); /** * @dev Reverts when the pool ID does not exist. */ modifier isExsistentVsErc20Pool(bytes32 poolID) { require( _vsErc20Pool[poolID].seller != address(0), "the exchange pair does not exist" ); _; } /** * @notice Exchange buyer's ERC20 token to the seller's bond. * @dev Ensure the seller has approved sufficient bonds and * you approve ERC20 token to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param swapPairAmount is the exchange pair token amount to pay. * @param expectedAmount is the bond amount to receive. * @param range (decimal: 3) */ function exchangeErc20ToBond( bytes32 bondID, bytes32 poolID, uint256 swapPairAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 bondAmount) { bondAmount = _exchangeErc20ToBond( msg.sender, bondID, poolID, swapPairAmount ); // assert(bondAmount != 0); _assertExpectedPriceRange(bondAmount, expectedAmount, range); } /** * @notice Exchange buyer's bond to the seller's ERC20 token. * @dev Ensure the seller has approved sufficient ERC20 token and * you approve bonds to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @param expectedAmount is the exchange pair token amount to receive. * @param range (decimal: 3) */ function exchangeBondToErc20( bytes32 bondID, bytes32 poolID, uint256 bondAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 swapPairAmount) { swapPairAmount = _exchangeBondToErc20( msg.sender, bondID, poolID, bondAmount ); // assert(swapPairAmount != 0); _assertExpectedPriceRange(swapPairAmount, expectedAmount, range); } /** * @notice Returns the exchange rate including spread. */ function calcRateBondToErc20(bytes32 bondID, bytes32 poolID) external returns (uint256 rateE8) { (rateE8, , , ) = _calcRateBondToErc20(bondID, poolID); } /** * @notice Returns pool ID generated by the immutable pool settings. */ function generateVsErc20PoolID( address seller, address swapPairAddress, bool isBondSale ) external view returns (bytes32 poolID) { return _generateVsErc20PoolID(seller, swapPairAddress, isBondSale); } /** * @notice Register a new vsErc20Pool. */ function createVsErc20Pool( ERC20 swapPairAddress, LatestPriceOracleInterface swapPairOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) external returns (bytes32 poolID) { return _createVsErc20Pool( msg.sender, swapPairAddress, swapPairOracleAddress, bondPricerAddress, feeBaseE4, isBondSale ); } /** * @notice Update the mutable pool settings. */ function updateVsErc20Pool( bytes32 poolID, LatestPriceOracleInterface swapPairOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external { require( _vsErc20Pool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _updateVsErc20Pool( poolID, swapPairOracleAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Delete the pool settings. */ function deleteVsErc20Pool(bytes32 poolID) external { require( _vsErc20Pool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsErc20Pool(poolID); } /** * @notice Returns the pool settings. */ function getVsErc20Pool(bytes32 poolID) external view returns ( address seller, ERC20 swapPairAddress, LatestPriceOracleInterface swapPairOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) { return _getVsErc20Pool(poolID); } /** * @dev Exchange buyer's ERC20 token to the seller's bond. * Ensure the seller has approved sufficient bonds and * buyer approve ERC20 token to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param swapPairAmount is the exchange pair token amount to pay. * @return bondAmount is the received bond amount. */ function _exchangeErc20ToBond( address buyer, bytes32 bondID, bytes32 poolID, uint256 swapPairAmount ) internal returns (uint256 bondAmount) { ( address seller, ERC20 swapPairToken, , , , bool isBondSale ) = _getVsErc20Pool(poolID); require(isBondSale, "This pool is for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { ( uint256 rateE8, , uint256 swapPairPriceE8, ) = _calcRateBondToErc20(bondID, poolID); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); uint8 decimalsOfSwapPair = swapPairToken.decimals(); bondAmount = _applyDecimalGap( swapPairAmount, decimalsOfSwapPair, DECIMALS_OF_BOND + 8 ) / rateE8; require(bondAmount != 0, "must transfer non-zero bond amount"); volumeE8 = swapPairPriceE8.mul(swapPairAmount).div( 10**uint256(decimalsOfSwapPair) ); } require( bondToken.transferFrom(seller, buyer, bondAmount), "fail to transfer bonds" ); swapPairToken.safeTransferFrom(buyer, seller, swapPairAmount); emit LogExchangeErc20ToBond( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } /** * @dev Exchange buyer's bond to the seller's ERC20 token. * Ensure the seller has approved sufficient ERC20 token and * buyer approve bonds to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @return swapPairAmount is the received swap pair token amount. */ function _exchangeBondToErc20( address buyer, bytes32 bondID, bytes32 poolID, uint256 bondAmount ) internal returns (uint256 swapPairAmount) { ( address seller, ERC20 swapPairToken, , , , bool isBondSale ) = _getVsErc20Pool(poolID); require(!isBondSale, "This pool is not for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { (uint256 rateE8, uint256 bondPriceE8, , ) = _calcRateBondToErc20( bondID, poolID ); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); uint8 decimalsOfSwapPair = swapPairToken.decimals(); swapPairAmount = _applyDecimalGap( bondAmount.mul(rateE8), DECIMALS_OF_BOND + 8, decimalsOfSwapPair ); require(swapPairAmount != 0, "must transfer non-zero token amount"); volumeE8 = bondPriceE8.mul(bondAmount).div( 10**uint256(DECIMALS_OF_BOND) ); } require( bondToken.transferFrom(buyer, seller, bondAmount), "fail to transfer bonds" ); swapPairToken.safeTransferFrom(seller, buyer, swapPairAmount); emit LogExchangeBondToErc20( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } function _calcRateBondToErc20(bytes32 bondID, bytes32 poolID) internal returns ( uint256 rateE8, uint256 bondPriceE8, uint256 swapPairPriceE8, int256 spreadE8 ) { ( , , LatestPriceOracleInterface erc20Oracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) = _getVsErc20Pool(poolID); swapPairPriceE8 = _getLatestPrice(erc20Oracle); (bondPriceE8, spreadE8) = _calcBondPriceAndSpread( bondPricer, bondID, feeBaseE4 ); bondPriceE8 = _calcUsdPrice(bondPriceE8); rateE8 = bondPriceE8.mul(10**8).div( swapPairPriceE8, "ERC20 oracle price must be non-zero" ); // `spreadE8` is less than 0.15 * 10**8. if (isBondSale) { rateE8 = rateE8.mul(uint256(10**8 + spreadE8)) / 10**8; } else { rateE8 = rateE8.mul(10**8) / uint256(10**8 + spreadE8); } } function _generateVsErc20PoolID( address seller, address swapPairAddress, bool isBondSale ) internal view returns (bytes32 poolID) { return keccak256( abi.encode( "Bond vs ERC20 exchange", address(this), seller, swapPairAddress, isBondSale ) ); } function _setVsErc20Pool( bytes32 poolID, address seller, ERC20 swapPairToken, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal { require(seller != address(0), "the pool ID already exists"); require( address(swapPairToken) != address(0), "swapPairToken should be non-zero address" ); require( address(swapPairOracle) != address(0), "swapPairOracle should be non-zero address" ); require( address(bondPricer) != address(0), "bondPricer should be non-zero address" ); _vsErc20Pool[poolID] = VsErc20Pool({ seller: seller, swapPairToken: swapPairToken, swapPairOracle: swapPairOracle, bondPricer: bondPricer, feeBaseE4: feeBaseE4, isBondSale: isBondSale }); } function _createVsErc20Pool( address seller, ERC20 swapPairToken, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal returns (bytes32 poolID) { poolID = _generateVsErc20PoolID( seller, address(swapPairToken), isBondSale ); require( _vsErc20Pool[poolID].seller == address(0), "the pool ID already exists" ); { uint256 price = _getLatestPrice(swapPairOracle); require( price != 0, "swapPairOracle has latestPrice() function which returns non-zero value" ); } _setVsErc20Pool( poolID, seller, swapPairToken, swapPairOracle, bondPricer, feeBaseE4, isBondSale ); if (isBondSale) { emit LogCreateErc20ToBondPool( poolID, seller, address(swapPairToken) ); } else { emit LogCreateBondToErc20Pool( poolID, seller, address(swapPairToken) ); } emit LogUpdateVsErc20Pool( poolID, address(swapPairOracle), address(bondPricer), feeBaseE4 ); } function _updateVsErc20Pool( bytes32 poolID, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal isExsistentVsErc20Pool(poolID) { ( address seller, ERC20 swapPairToken, , , , bool isBondSale ) = _getVsErc20Pool(poolID); _setVsErc20Pool( poolID, seller, swapPairToken, swapPairOracle, bondPricer, feeBaseE4, isBondSale ); emit LogUpdateVsErc20Pool( poolID, address(swapPairOracle), address(bondPricer), feeBaseE4 ); } function _deleteVsErc20Pool(bytes32 poolID) internal isExsistentVsErc20Pool(poolID) { delete _vsErc20Pool[poolID]; emit LogDeleteVsErc20Pool(poolID); } function _getVsErc20Pool(bytes32 poolID) internal view isExsistentVsErc20Pool(poolID) returns ( address seller, ERC20 swapPairToken, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) { VsErc20Pool memory exchangePair = _vsErc20Pool[poolID]; seller = exchangePair.seller; swapPairToken = exchangePair.swapPairToken; swapPairOracle = exchangePair.swapPairOracle; bondPricer = exchangePair.bondPricer; feeBaseE4 = exchangePair.feeBaseE4; isBondSale = exchangePair.isBondSale; } } // File: contracts/util/TransferETH.sol pragma solidity 0.6.6; abstract contract TransferETH is TransferETHInterface { receive() external payable override { emit LogTransferETH(msg.sender, address(this), msg.value); } function _hasSufficientBalance(uint256 amount) internal view returns (bool ok) { address thisContract = address(this); return amount <= thisContract.balance; } /** * @notice transfer `amount` ETH to the `recipient` account with emitting log */ function _transferETH( address payable recipient, uint256 amount, string memory errorMessage ) internal { require(_hasSufficientBalance(amount), errorMessage); (bool success, ) = recipient.call{value: amount}(""); // solhint-disable-line avoid-low-level-calls require(success, "transferring Ether failed"); emit LogTransferETH(address(this), recipient, amount); } function _transferETH(address payable recipient, uint256 amount) internal { _transferETH(recipient, amount, "TransferETH: transfer amount exceeds balance"); } } // File: contracts/generalizedDotc/BondVsEthExchange.sol pragma solidity 0.6.6; abstract contract BondVsEthExchange is BondExchange, TransferETH { uint8 internal constant DECIMALS_OF_ETH = 18; struct VsEthPool { address seller; LatestPriceOracleInterface ethOracle; BondPricerInterface bondPricer; int16 feeBaseE4; bool isBondSale; } mapping(bytes32 => VsEthPool) internal _vsEthPool; mapping(address => uint256) internal _depositedEth; event LogCreateEthToBondPool( bytes32 indexed poolID, address indexed seller ); event LogCreateBondToEthPool( bytes32 indexed poolID, address indexed seller ); event LogUpdateVsEthPool( bytes32 indexed poolID, address ethOracleAddress, address bondPricerAddress, int16 feeBase // decimal: 4 ); event LogDeleteVsEthPool(bytes32 indexed poolID); event LogExchangeEthToBond( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: 18 uint256 volume // USD, decimal: 8 ); event LogExchangeBondToEth( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: 18 uint256 volume // USD, decimal: 8 ); /** * @dev Reverts when the pool ID does not exist. */ modifier isExsistentVsEthPool(bytes32 poolID) { require( _vsEthPool[poolID].seller != address(0), "the exchange pair does not exist" ); _; } /** * @notice Exchange buyer's ETH to the seller's bond. * @dev Ensure the seller has approved sufficient bonds and * you deposit ETH to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param ethAmount is the exchange pair token amount to pay. * @param expectedAmount is the bond amount to receive. * @param range (decimal: 3) */ function exchangeEthToBond( bytes32 bondID, bytes32 poolID, uint256 ethAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 bondAmount) { bondAmount = _exchangeEthToBond(msg.sender, bondID, poolID, ethAmount); // assert(bondAmount != 0); _assertExpectedPriceRange(bondAmount, expectedAmount, range); } /** * @notice Exchange buyer's bond to the seller's ETH. * @dev Ensure the seller has deposited sufficient ETH and * you approve bonds to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @param expectedAmount is the ETH amount to receive. * @param range (decimal: 3) */ function exchangeBondToEth( bytes32 bondID, bytes32 poolID, uint256 bondAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 ethAmount) { ethAmount = _exchangeBondToEth(msg.sender, bondID, poolID, bondAmount); // assert(ethAmount != 0); _assertExpectedPriceRange(ethAmount, expectedAmount, range); } /** * @notice Returns the exchange rate including spread. */ function calcRateBondToEth(bytes32 bondID, bytes32 poolID) external returns (uint256 rateE8) { (rateE8, , , ) = _calcRateBondToEth(bondID, poolID); } /** * @notice Returns pool ID generated by the immutable pool settings. */ function generateVsEthPoolID(address seller, bool isBondSale) external view returns (bytes32 poolID) { return _generateVsEthPoolID(seller, isBondSale); } /** * @notice Register a new vsEthPool. */ function createVsEthPool( LatestPriceOracleInterface ethOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) external returns (bytes32 poolID) { return _createVsEthPool( msg.sender, ethOracleAddress, bondPricerAddress, feeBaseE4, isBondSale ); } /** * @notice Update the mutable pool settings. */ function updateVsEthPool( bytes32 poolID, LatestPriceOracleInterface ethOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external { require( _vsEthPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _updateVsEthPool( poolID, ethOracleAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Delete the pool settings. */ function deleteVsEthPool(bytes32 poolID) external { require( _vsEthPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsEthPool(poolID); } /** * @notice Returns the pool settings. */ function getVsEthPool(bytes32 poolID) external view returns ( address seller, LatestPriceOracleInterface ethOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) { return _getVsEthPool(poolID); } /** * @notice Transfer ETH to this contract and allow this contract to pay ETH when exchanging. */ function depositEth() external payable { _addEthAllowance(msg.sender, msg.value); } /** * @notice Withdraw all deposited ETH. */ function withdrawEth() external returns (uint256 amount) { amount = _depositedEth[msg.sender]; _transferEthFrom(msg.sender, msg.sender, amount); } /** * @notice Returns deposited ETH amount. */ function ethAllowance(address owner) external view returns (uint256 amount) { amount = _depositedEth[owner]; } /** * @dev Exchange buyer's ETH to the seller's bond. * Ensure the seller has approved sufficient bonds and * buyer deposit ETH to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param swapPairAmount is the exchange pair token amount to pay. * @return bondAmount is the received bond amount. */ function _exchangeEthToBond( address buyer, bytes32 bondID, bytes32 poolID, uint256 swapPairAmount ) internal returns (uint256 bondAmount) { (address seller, , , , bool isBondSale) = _getVsEthPool(poolID); require(isBondSale, "This pool is for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { (uint256 rateE8, , uint256 swapPairPriceE8, ) = _calcRateBondToEth( bondID, poolID ); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); bondAmount = _applyDecimalGap( swapPairAmount, DECIMALS_OF_ETH, DECIMALS_OF_BOND + 8 ) / rateE8; require(bondAmount != 0, "must transfer non-zero bond amount"); volumeE8 = swapPairPriceE8.mul(swapPairAmount).div( 10**uint256(DECIMALS_OF_ETH) ); } require( bondToken.transferFrom(seller, buyer, bondAmount), "fail to transfer bonds" ); _transferEthFrom(buyer, seller, swapPairAmount); emit LogExchangeEthToBond( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } /** * @dev Exchange buyer's bond to the seller's ETH. * Ensure the seller has deposited sufficient ETH and * buyer approve bonds to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @return swapPairAmount is the received ETH amount. */ function _exchangeBondToEth( address buyer, bytes32 bondID, bytes32 poolID, uint256 bondAmount ) internal returns (uint256 swapPairAmount) { (address seller, , , , bool isBondSale) = _getVsEthPool(poolID); require(!isBondSale, "This pool is not for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { (uint256 rateE8, uint256 bondPriceE8, , ) = _calcRateBondToEth( bondID, poolID ); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); swapPairAmount = _applyDecimalGap( bondAmount.mul(rateE8), DECIMALS_OF_BOND + 8, DECIMALS_OF_ETH ); require(swapPairAmount != 0, "must transfer non-zero token amount"); volumeE8 = bondPriceE8.mul(bondAmount).div( 10**uint256(DECIMALS_OF_BOND) ); } require( bondToken.transferFrom(buyer, seller, bondAmount), "fail to transfer bonds" ); _transferEthFrom(seller, buyer, swapPairAmount); emit LogExchangeBondToEth( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } function _calcRateBondToEth(bytes32 bondID, bytes32 poolID) internal returns ( uint256 rateE8, uint256 bondPriceE8, uint256 swapPairPriceE8, int256 spreadE8 ) { ( , LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) = _getVsEthPool(poolID); swapPairPriceE8 = _getLatestPrice(ethOracle); (bondPriceE8, spreadE8) = _calcBondPriceAndSpread( bondPricer, bondID, feeBaseE4 ); bondPriceE8 = _calcUsdPrice(bondPriceE8); rateE8 = bondPriceE8.mul(10**8).div( swapPairPriceE8, "ERC20 oracle price must be non-zero" ); // `spreadE8` is less than 0.15 * 10**8. if (isBondSale) { rateE8 = rateE8.mul(uint256(10**8 + spreadE8)) / 10**8; } else { rateE8 = rateE8.mul(uint256(10**8 - spreadE8)) / 10**8; } } function _generateVsEthPoolID(address seller, bool isBondSale) internal view returns (bytes32 poolID) { return keccak256( abi.encode( "Bond vs ETH exchange", address(this), seller, isBondSale ) ); } function _setVsEthPool( bytes32 poolID, address seller, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal { require(seller != address(0), "the pool ID already exists"); require( address(ethOracle) != address(0), "ethOracle should be non-zero address" ); require( address(bondPricer) != address(0), "bondPricer should be non-zero address" ); _vsEthPool[poolID] = VsEthPool({ seller: seller, ethOracle: ethOracle, bondPricer: bondPricer, feeBaseE4: feeBaseE4, isBondSale: isBondSale }); } function _createVsEthPool( address seller, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal returns (bytes32 poolID) { poolID = _generateVsEthPoolID(seller, isBondSale); require( _vsEthPool[poolID].seller == address(0), "the pool ID already exists" ); { uint256 price = ethOracle.latestPrice(); require( price != 0, "ethOracle has latestPrice() function which returns non-zero value" ); } _setVsEthPool( poolID, seller, ethOracle, bondPricer, feeBaseE4, isBondSale ); if (isBondSale) { emit LogCreateEthToBondPool(poolID, seller); } else { emit LogCreateBondToEthPool(poolID, seller); } emit LogUpdateVsEthPool( poolID, address(ethOracle), address(bondPricer), feeBaseE4 ); } function _updateVsEthPool( bytes32 poolID, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal isExsistentVsEthPool(poolID) { (address seller, , , , bool isBondSale) = _getVsEthPool(poolID); _setVsEthPool( poolID, seller, ethOracle, bondPricer, feeBaseE4, isBondSale ); emit LogUpdateVsEthPool( poolID, address(ethOracle), address(bondPricer), feeBaseE4 ); } function _deleteVsEthPool(bytes32 poolID) internal isExsistentVsEthPool(poolID) { delete _vsEthPool[poolID]; emit LogDeleteVsEthPool(poolID); } function _getVsEthPool(bytes32 poolID) internal view isExsistentVsEthPool(poolID) returns ( address seller, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) { VsEthPool memory exchangePair = _vsEthPool[poolID]; seller = exchangePair.seller; ethOracle = exchangePair.ethOracle; bondPricer = exchangePair.bondPricer; feeBaseE4 = exchangePair.feeBaseE4; isBondSale = exchangePair.isBondSale; } function _transferEthFrom( address sender, address recipient, uint256 amount ) internal { _subEthAllowance(sender, amount); _transferETH(payable(recipient), amount); } function _addEthAllowance(address sender, uint256 amount) internal { _depositedEth[sender] += amount; require(_depositedEth[sender] >= amount, "overflow allowance"); } function _subEthAllowance(address owner, uint256 amount) internal { require(_depositedEth[owner] >= amount, "insufficient allowance"); _depositedEth[owner] -= amount; } } // File: contracts/generalizedDotc/BondVsBondExchange.sol pragma solidity 0.6.6; abstract contract BondVsBondExchange is BondExchange { /** * @dev the sum of decimalsOfBond and decimalsOfOraclePrice of the bondMaker. * This value is constant by the restriction of `_assertBondMakerDecimals`. */ uint8 internal constant DECIMALS_OF_BOND_VALUE = DECIMALS_OF_BOND + DECIMALS_OF_ORACLE_PRICE; struct VsBondPool { address seller; BondMakerInterface bondMakerForUser; VolatilityOracleInterface volatilityOracle; BondPricerInterface bondPricerForUser; BondPricerInterface bondPricer; int16 feeBaseE4; } mapping(bytes32 => VsBondPool) internal _vsBondPool; event LogCreateBondToBondPool( bytes32 indexed poolID, address indexed seller, address indexed bondMakerForUser ); event LogUpdateVsBondPool( bytes32 indexed poolID, address bondPricerForUser, address bondPricer, int16 feeBase // decimal: 4 ); event LogDeleteVsBondPool(bytes32 indexed poolID); event LogExchangeBondToBond( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // USD, decimal: 8 uint256 volume // USD, decimal: 8 ); /** * @dev Reverts when the pool ID does not exist. */ modifier isExsistentVsBondPool(bytes32 poolID) { require( _vsBondPool[poolID].seller != address(0), "the exchange pair does not exist" ); _; } /** * @notice Exchange the seller's bond to buyer's multiple bonds. * @dev Ensure the seller has approved sufficient bonds and * Approve bonds to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param amountInDollarsE8 is the exchange pair token amount to pay. (decimals: 8) * @param expectedAmount is the bond amount to receive. (decimals: 8) * @param range (decimal: 3) */ function exchangeBondToBond( bytes32 bondID, bytes32 poolID, bytes32[] calldata bondIDs, uint256 amountInDollarsE8, uint256 expectedAmount, uint256 range ) external returns (uint256 bondAmount) { uint256 amountInDollars = _applyDecimalGap( amountInDollarsE8, 8, DECIMALS_OF_BOND_VALUE ); bondAmount = _exchangeBondToBond( msg.sender, bondID, poolID, bondIDs, amountInDollars ); _assertExpectedPriceRange(bondAmount, expectedAmount, range); } /** * @notice Returns the exchange rate including spread. */ function calcRateBondToUsd(bytes32 bondID, bytes32 poolID) external returns (uint256 rateE8) { (rateE8, , , ) = _calcRateBondToUsd(bondID, poolID); } /** * @notice Returns pool ID generated by the immutable pool settings. */ function generateVsBondPoolID(address seller, address bondMakerForUser) external view returns (bytes32 poolID) { return _generateVsBondPoolID(seller, bondMakerForUser); } /** * @notice Register a new vsBondPool. */ function createVsBondPool( BondMakerInterface bondMakerForUserAddress, VolatilityOracleInterface volatilityOracleAddress, BondPricerInterface bondPricerForUserAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external returns (bytes32 poolID) { return _createVsBondPool( msg.sender, bondMakerForUserAddress, volatilityOracleAddress, bondPricerForUserAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Update the mutable pool settings. */ function updateVsBondPool( bytes32 poolID, VolatilityOracleInterface volatilityOracleAddress, BondPricerInterface bondPricerForUserAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external { require( _vsBondPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _updateVsBondPool( poolID, volatilityOracleAddress, bondPricerForUserAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Delete the pool settings. */ function deleteVsBondPool(bytes32 poolID) external { require( _vsBondPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsBondPool(poolID); } /** * @notice Returns the pool settings. */ function getVsBondPool(bytes32 poolID) external view returns ( address seller, BondMakerInterface bondMakerForUserAddress, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUserAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) { return _getVsBondPool(poolID); } /** * @notice Returns the total approved bond amount in U.S. dollars. * Unnecessary bond must not be included in bondIDs. */ function totalBondAllowance( bytes32 poolID, bytes32[] calldata bondIDs, uint256 maturityBorder, address owner ) external returns (uint256 allowanceInDollarsE8) { ( , BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, , , ) = _getVsBondPool(poolID); uint256 allowanceInDollars = _totalBondAllowance( bondMakerForUser, volatilityOracle, bondPricerForUser, bondIDs, maturityBorder, owner ); allowanceInDollarsE8 = _applyDecimalGap( allowanceInDollars, DECIMALS_OF_BOND_VALUE, 8 ); } /** * @dev Exchange the seller's bond to buyer's multiple bonds. * Ensure the seller has approved sufficient bonds and * buyer approve bonds to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param amountInDollars is the exchange pair token amount to pay. (decimals: 16) * @return bondAmount is the received bond amount. */ function _exchangeBondToBond( address buyer, bytes32 bondID, bytes32 poolID, bytes32[] memory bondIDs, uint256 amountInDollars ) internal returns (uint256 bondAmount) { require(bondIDs.length != 0, "must input bonds for payment"); BondMakerInterface bondMakerForUser; { bool isBondSale; (, bondMakerForUser, , , , , isBondSale) = _getVsBondPool(poolID); require(isBondSale, "This pool is for buying bond"); } (ERC20 bondToken, uint256 maturity, , ) = _getBond( _bondMakerContract, bondID ); require(address(bondToken) != address(0), "the bond is not registered"); { (uint256 rateE8, , , ) = _calcRateBondToUsd(bondID, poolID); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); bondAmount = _applyDecimalGap( amountInDollars, DECIMALS_OF_BOND_VALUE, bondToken.decimals() + 8 ) / rateE8; require(bondAmount != 0, "must transfer non-zero bond amount"); } { ( address seller, , VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, , , ) = _getVsBondPool(poolID); require( bondToken.transferFrom(seller, buyer, bondAmount), "fail to transfer bonds" ); address buyerTmp = buyer; // avoid `stack too deep` error uint256 amountInDollarsTmp = amountInDollars; // avoid `stack too deep` error require( _batchTransferBondFrom( bondMakerForUser, volatilityOracle, bondPricerForUser, bondIDs, maturity, buyerTmp, seller, amountInDollarsTmp ), "fail to transfer ERC20 token" ); } uint256 volumeE8 = _applyDecimalGap( amountInDollars, DECIMALS_OF_BOND_VALUE, 8 ); emit LogExchangeBondToBond( buyer, bondID, poolID, bondAmount, amountInDollars, volumeE8 ); } function _calcRateBondToUsd(bytes32 bondID, bytes32 poolID) internal returns ( uint256 rateE8, uint256 bondPriceE8, uint256 swapPairPriceE8, int256 spreadE8 ) { ( , , , , BondPricerInterface bondPricer, int16 feeBaseE4, ) = _getVsBondPool(poolID); (bondPriceE8, spreadE8) = _calcBondPriceAndSpread( bondPricer, bondID, feeBaseE4 ); bondPriceE8 = _calcUsdPrice(bondPriceE8); swapPairPriceE8 = 10**8; rateE8 = bondPriceE8.mul(uint256(10**8 + spreadE8)) / 10**8; } function _generateVsBondPoolID(address seller, address bondMakerForUser) internal view returns (bytes32 poolID) { return keccak256( abi.encode( "Bond vs SBT exchange", address(this), seller, bondMakerForUser ) ); } function _setVsBondPool( bytes32 poolID, address seller, BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal { require(seller != address(0), "the pool ID already exists"); require( address(bondMakerForUser) != address(0), "bondMakerForUser should be non-zero address" ); require( address(bondPricerForUser) != address(0), "bondPricerForUser should be non-zero address" ); require( address(bondPricer) != address(0), "bondPricer should be non-zero address" ); _assertBondMakerDecimals(bondMakerForUser); _vsBondPool[poolID] = VsBondPool({ seller: seller, bondMakerForUser: bondMakerForUser, volatilityOracle: volatilityOracle, bondPricerForUser: bondPricerForUser, bondPricer: bondPricer, feeBaseE4: feeBaseE4 }); } function _createVsBondPool( address seller, BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal returns (bytes32 poolID) { poolID = _generateVsBondPoolID(seller, address(bondMakerForUser)); require( _vsBondPool[poolID].seller == address(0), "the pool ID already exists" ); _assertBondMakerDecimals(bondMakerForUser); _setVsBondPool( poolID, seller, bondMakerForUser, volatilityOracle, bondPricerForUser, bondPricer, feeBaseE4 ); emit LogCreateBondToBondPool(poolID, seller, address(bondMakerForUser)); emit LogUpdateVsBondPool( poolID, address(bondPricerForUser), address(bondPricer), feeBaseE4 ); } function _updateVsBondPool( bytes32 poolID, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal isExsistentVsBondPool(poolID) { ( address seller, BondMakerInterface bondMakerForUser, , , , , ) = _getVsBondPool(poolID); _setVsBondPool( poolID, seller, bondMakerForUser, volatilityOracle, bondPricerForUser, bondPricer, feeBaseE4 ); emit LogUpdateVsBondPool( poolID, address(bondPricerForUser), address(bondPricer), feeBaseE4 ); } function _deleteVsBondPool(bytes32 poolID) internal isExsistentVsBondPool(poolID) { delete _vsBondPool[poolID]; emit LogDeleteVsBondPool(poolID); } function _getVsBondPool(bytes32 poolID) internal view isExsistentVsBondPool(poolID) returns ( address seller, BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) { VsBondPool memory exchangePair = _vsBondPool[poolID]; seller = exchangePair.seller; bondMakerForUser = exchangePair.bondMakerForUser; volatilityOracle = exchangePair.volatilityOracle; bondPricerForUser = exchangePair.bondPricerForUser; bondPricer = exchangePair.bondPricer; feeBaseE4 = exchangePair.feeBaseE4; isBondSale = true; } /** * @dev Transfer multiple bonds in one method. * Unnecessary bonds can be included in bondIDs. */ function _batchTransferBondFrom( BondMakerInterface bondMaker, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricer, bytes32[] memory bondIDs, uint256 maturityBorder, address sender, address recipient, uint256 amountInDollars ) internal returns (bool ok) { uint256 oraclePriceE8 = _getLatestPrice(bondMaker.oracleAddress()); uint256 rest = amountInDollars; // mutable for (uint256 i = 0; i < bondIDs.length; i++) { ERC20 bond; uint256 oracleVolE8; { uint256 maturity; (bond, maturity, , ) = _getBond(bondMaker, bondIDs[i]); if (maturity > maturityBorder) continue; // skip transaction uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); oracleVolE8 = _getVolatility( volatilityOracle, untilMaturity.toUint64() ); } uint256 allowance = bond.allowance(sender, address(this)); if (allowance == 0) continue; // skip transaction BondMakerInterface bondMakerTmp = bondMaker; // avoid `stack too deep` error BondPricerInterface bondPricerTmp = bondPricer; // avoid `stack too deep` error bytes32 bondIDTmp = bondIDs[i]; // avoid `stack too deep` error uint256 bondPrice = _calcBondPrice( bondMakerTmp, bondPricerTmp, bondIDTmp, oraclePriceE8, oracleVolE8 ); if (bondPrice == 0) continue; // skip transaction if (rest <= allowance.mul(bondPrice)) { // assert(ceil(rest / bondPrice) <= allowance); return bond.transferFrom( sender, recipient, rest.divRoundUp(bondPrice) ); } require( bond.transferFrom(sender, recipient, allowance), "fail to transfer bonds" ); rest -= allowance * bondPrice; } revert("insufficient bond allowance"); } /** * @dev Returns the total approved bond amount in U.S. dollars. * Unnecessary bond must not be included in bondIDs. */ function _totalBondAllowance( BondMakerInterface bondMaker, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricer, bytes32[] memory bondIDs, uint256 maturityBorder, address sender ) internal returns (uint256 allowanceInDollars) { uint256 oraclePriceE8 = _getLatestPrice(bondMaker.oracleAddress()); for (uint256 i = 0; i < bondIDs.length; i++) { ERC20 bond; uint256 oracleVolE8; { uint256 maturity; (bond, maturity, , ) = _getBond(bondMaker, bondIDs[i]); if (maturity > maturityBorder) continue; // skip uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); oracleVolE8 = _getVolatility( volatilityOracle, untilMaturity.toUint64() ); } uint256 balance = bond.balanceOf(sender); require(balance != 0, "includes no bond balance"); uint256 allowance = bond.allowance(sender, address(this)); require(allowance != 0, "includes no approved bond"); uint256 bondPrice = _calcBondPrice( bondMaker, bondPricer, bondIDs[i], oraclePriceE8, oracleVolE8 ); require(bondPrice != 0, "includes worthless bond"); allowanceInDollars = allowanceInDollars.add( allowance.mul(bondPrice) ); } } /** * @dev Calculate bond price by bond ID. */ function _calcBondPrice( BondMakerInterface bondMaker, BondPricerInterface bondPricer, bytes32 bondID, uint256 oraclePriceE8, uint256 oracleVolatilityE8 ) internal view returns (uint256) { int256 untilMaturity; { (, uint256 maturity, , ) = _getBond(bondMaker, bondID); untilMaturity = maturity .sub( _getBlockTimestampSec(), "the bond should not have expired" ) .toInt256(); } BondType bondType; uint256[] memory points; { bool isKnownBondType; (isKnownBondType, bondType, points) = _bondShapeDetector .getBondTypeByID(bondMaker, bondID, BondType.NONE); if (!isKnownBondType) { revert("unknown bond type"); // return 0; } } try bondPricer.calcPriceAndLeverage( bondType, points, oraclePriceE8.toInt256(), oracleVolatilityE8.toInt256(), untilMaturity ) returns (uint256 bondPriceE8, uint256) { return bondPriceE8; } catch { return 0; } } } // File: contracts/generalizedDotc/GeneralizedDotc.sol pragma solidity 0.6.6; contract GeneralizedDotc is BondVsBondExchange, BondVsErc20Exchange, BondVsEthExchange { constructor( BondMakerInterface bondMakerAddress, VolatilityOracleInterface volatilityOracleAddress, LatestPriceOracleInterface volumeCalculatorAddress, DetectBondShape bondShapeDetector ) public BondExchange( bondMakerAddress, volatilityOracleAddress, volumeCalculatorAddress, bondShapeDetector ) {} }
Returns bond tokenaddress, maturity,/ Revert if `bondTokenAddress` is zero.
function _getBond(BondMakerInterface bondMaker, bytes32 bondID) internal view returns ( ERC20 bondToken, uint256 maturity, uint256 sbtStrikePrice, bytes32 fnMapID ) { address bondTokenAddress; (bondTokenAddress, maturity, sbtStrikePrice, fnMapID) = bondMaker .getBond(bondID); bondToken = ERC20(bondTokenAddress); }
6,770,759
./full_match/42220/0x88FAcCc7D0C4148A73D2cC626e8192F4ba95F1C7/sources/contracts/Gelato.sol
Create a timed task that executes every so often based on the inputted interval _startTime Timestamp when the first task should become executable. 0 for right now _interval After how many seconds should each task be executed _execAddress On which contract should Gelato execute the transactions _execSelector Which function Gelato should eecute on the _execAddress _resolverAddress On which contract should Gelato check when to execute the tx _resolverData Which data should be used to check on the Resolver when to execute the tx _feeToken Which token to use as fee payment _useTreasury True if Gelato should charge fees from TaskTreasury, false if not
function createTimedTask( uint128 _startTime, uint128 _interval, address _execAddress, bytes4 _execSelector, bytes calldata _execCommand, address _resolverAddress, bytes calldata _resolverData, address _feeToken, bool _useTreasury ) public returns (bytes32 task) { require(_interval > 0, "Ops: createTimedTask: interval cannot be 0"); if (_useTreasury) { task = createTask( _execAddress, _execSelector, _execCommand, _resolverAddress, _resolverData ); task = createTaskNoPrepayment( _execAddress, _execSelector, _execCommand, _resolverAddress, _resolverData, _feeToken ); } uint128 nextExec = uint256(_startTime) > block.timestamp ? _startTime : uint128(block.timestamp); emit TimerSet(task, nextExec, _interval); }
16,352,404
./full_match/1/0x5D8d9F5b96f4438195BE9b99eee6118Ed4304286/sources/contracts/Blacksmith.sol
collect dust to treasury
function collectDust(address _token) external override { Pool memory pool = pools[_token]; require(pool.lastUpdatedAt == 0, "Blacksmith: lpToken, not allowed"); require(allowBonusTokens[_token] == 0, "Blacksmith: bonusToken, not allowed"); IERC20 token = IERC20(_token); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "Blacksmith: 0 to collect"); payable(treasury).transfer(amount); token.safeTransfer(treasury, amount); }
2,907,514
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul interface DharmaTradeReserveV9Interface { event ROLEMODIFIED858(Role indexed role, address account); //inject NONSTANDARD NAMING event ROLEPAUSED516(Role indexed role); //inject NONSTANDARD NAMING event ROLEUNPAUSED425(Role indexed role); //inject NONSTANDARD NAMING event ETHERRECEIVED855(address sender, uint256 amount); //inject NONSTANDARD NAMING enum Role { // # DEPOSIT_MANAGER, // 0 ADJUSTER, // 1 WITHDRAWAL_MANAGER, // 2 RESERVE_TRADER, // 3 PAUSER // 4 } struct RoleStatus { address account; bool paused; } function TRADEDAIFORETHER899( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEDAIFORETHERV2950( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEETHERFORDAI795( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought); function TRADEETHERFORDAIV2625( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought); function TRADEDAIFORTOKEN107( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function TRADETOKENFORDAI864( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought); function TRADETOKENFORETHER84( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function TRADEETHERFORTOKEN818( //inject NONSTANDARD NAMING address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold); function TRADEETHERFORTOKENUSINGETHERIZER867( //inject NONSTANDARD NAMING address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function TRADEDAIFORETHERUSINGRESERVES556( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEDAIFORETHERUSINGRESERVESV2121( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold); function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI322( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV298( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function TRADEDAIFORTOKENUSINGRESERVES528( //inject NONSTANDARD NAMING address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold); function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI549( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought, uint256 totalDDaiMinted); function TRADETOKENFORETHERUSINGRESERVES915( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought); function TRADEETHERFORTOKENUSINGRESERVES405( //inject NONSTANDARD NAMING address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold); function FINALIZEETHERDEPOSIT298( //inject NONSTANDARD NAMING address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external; function FINALIZEDAIDEPOSIT931( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external; function FINALIZEDHARMADAIDEPOSIT237( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external; function MINT835(uint256 daiAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING function REDEEM834(uint256 dDaiAmount) external returns (uint256 daiReceived); //inject NONSTANDARD NAMING function TRADEDDAIFORUSDC353( //inject NONSTANDARD NAMING uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external returns (uint256 usdcReceived); function TRADEUSDCFORDDAI141( //inject NONSTANDARD NAMING uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external returns (uint256 dDaiMinted); function WITHDRAWUSDC678(address recipient, uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDAI49(address recipient, uint256 daiAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDHARMADAI777(address recipient, uint256 dDaiAmount) external; //inject NONSTANDARD NAMING function WITHDRAWUSDCTOPRIMARYRECIPIENT422(uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWDAITOPRIMARYRECIPIENT762(uint256 usdcAmount) external; //inject NONSTANDARD NAMING function WITHDRAWETHER204( //inject NONSTANDARD NAMING address payable recipient, uint256 etherAmount ) external; function WITHDRAW439( //inject NONSTANDARD NAMING ERC20Interface token, address recipient, uint256 amount ) external returns (bool success); function CALLANY778( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external returns (bool ok, bytes memory returnData); function SETDAILIMIT345(uint256 daiAmount) external; //inject NONSTANDARD NAMING function SETETHERLIMIT550(uint256 daiAmount) external; //inject NONSTANDARD NAMING function SETPRIMARYUSDCRECIPIENT259(address recipient) external; //inject NONSTANDARD NAMING function SETPRIMARYDAIRECIPIENT972(address recipient) external; //inject NONSTANDARD NAMING function SETROLE712(Role role, address account) external; //inject NONSTANDARD NAMING function REMOVEROLE29(Role role) external; //inject NONSTANDARD NAMING function PAUSE504(Role role) external; //inject NONSTANDARD NAMING function UNPAUSE768(Role role) external; //inject NONSTANDARD NAMING function ISPAUSED423(Role role) external view returns (bool paused); //inject NONSTANDARD NAMING function ISROLE511(Role role) external view returns (bool hasRole); //inject NONSTANDARD NAMING function ISDHARMASMARTWALLET695( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet); function GETDEPOSITMANAGER250() external view returns (address depositManager); //inject NONSTANDARD NAMING function GETADJUSTER715() external view returns (address adjuster); //inject NONSTANDARD NAMING function GETRESERVETRADER735() external view returns (address reserveTrader); //inject NONSTANDARD NAMING function GETWITHDRAWALMANAGER7() external view returns (address withdrawalManager); //inject NONSTANDARD NAMING function GETPAUSER73() external view returns (address pauser); //inject NONSTANDARD NAMING function GETRESERVES254() external view returns ( //inject NONSTANDARD NAMING uint256 dai, uint256 dDai, uint256 dDaiUnderlying ); function GETDAILIMIT529() external view returns ( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 dDaiAmount ); function GETETHERLIMIT792() external view returns (uint256 etherAmount); //inject NONSTANDARD NAMING function GETPRIMARYUSDCRECIPIENT771() external view returns ( //inject NONSTANDARD NAMING address recipient ); function GETPRIMARYDAIRECIPIENT209() external view returns ( //inject NONSTANDARD NAMING address recipient ); function GETIMPLEMENTATION393() external view returns (address implementation); //inject NONSTANDARD NAMING function GETVERSION945() external view returns (uint256 version); //inject NONSTANDARD NAMING } interface ERC20Interface { function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE301(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE335(address, address) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER424(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM59(address, address, uint256) external returns (bool); //inject NONSTANDARD NAMING } interface DTokenInterface { function MINT835(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING function REDEEM834(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING function REDEEMUNDERLYING110(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING function BALANCEOF395(address) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFUNDERLYING111(address) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER424(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function APPROVE301(address, uint256) external returns (bool); //inject NONSTANDARD NAMING function EXCHANGERATECURRENT826() external view returns (uint256); //inject NONSTANDARD NAMING } interface TradeHelperInterface { function TRADEUSDCFORDDAI141(uint256 amountUSDC, uint256 quotedDaiEquivalentAmount) external returns (uint256 dDaiMinted); //inject NONSTANDARD NAMING function TRADEDDAIFORUSDC353(uint256 amountDai, uint256 quotedUSDCAmount) external returns (uint256 usdcReceived); //inject NONSTANDARD NAMING function GETEXPECTEDDAI468(uint256 usdc) external view returns (uint256 dai); //inject NONSTANDARD NAMING function GETEXPECTEDUSDC440(uint256 dai) external view returns (uint256 usdc); //inject NONSTANDARD NAMING } interface UniswapV1Interface { function ETHTOTOKENSWAPINPUT251( //inject NONSTANDARD NAMING uint256 minTokens, uint256 deadline ) external payable returns (uint256 tokensBought); function TOKENTOETHTRANSFEROUTPUT929( //inject NONSTANDARD NAMING uint256 ethBought, uint256 maxTokens, uint256 deadline, address recipient ) external returns (uint256 tokensSold); } interface UniswapV2Interface { function SWAPTOKENSFOREXACTTOKENS91( //inject NONSTANDARD NAMING uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPEXACTTOKENSFORTOKENS457( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPEXACTTOKENSFORETH769( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPTOKENSFOREXACTETH731( //inject NONSTANDARD NAMING uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function SWAPETHFOREXACTTOKENS5( //inject NONSTANDARD NAMING uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function SWAPEXACTETHFORTOKENS903( //inject NONSTANDARD NAMING uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface EtherReceiverInterface { function SETTLEETHER955() external; //inject NONSTANDARD NAMING } library SafeMath { function ADD510(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function MUL1(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, "SafeMath: division by zero"); return a / b; } } contract TwoStepOwnable { event OWNERSHIPTRANSFERRED461( //inject NONSTANDARD NAMING address indexed previousOwner, address indexed newOwner ); address private _owner; address private _newPotentialOwner; function TRANSFEROWNERSHIP1000(address newOwner) external ONLYOWNER389 { //inject NONSTANDARD NAMING require( newOwner != address(0), "TwoStepOwnable: new potential owner is the zero address." ); _newPotentialOwner = newOwner; } function CANCELOWNERSHIPTRANSFER705() external ONLYOWNER389 { //inject NONSTANDARD NAMING delete _newPotentialOwner; } function ACCEPTOWNERSHIP63() external { //inject NONSTANDARD NAMING require( msg.sender == _newPotentialOwner, "TwoStepOwnable: current owner must set caller as new potential owner." ); delete _newPotentialOwner; emit OWNERSHIPTRANSFERRED461(_owner, msg.sender); _owner = msg.sender; } function OWNER109() external view returns (address) { //inject NONSTANDARD NAMING return _owner; } function ISOWNER823() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } modifier ONLYOWNER389() { //inject NONSTANDARD NAMING require(ISOWNER823(), "TwoStepOwnable: caller is not the owner."); _; } } contract DharmaTradeReserveV9ImplementationStaging is DharmaTradeReserveV9Interface, TwoStepOwnable { using SafeMath for uint256; // Maintain a role status mapping with assigned accounts and paused states. mapping(uint256 => RoleStatus) private _roles; // Maintain a "primary recipient" the withdrawal manager can transfer Dai to. address private _primaryDaiRecipient; // Maintain a "primary recipient" the withdrawal manager can transfer USDC to. address private _primaryUSDCRecipient; // Maintain a maximum allowable transfer size (in Dai) for the deposit manager. uint256 private _daiLimit; // Maintain a maximum allowable transfer size (in Ether) for the deposit manager. uint256 private _etherLimit; bool private _originatesFromReserveTrader; // unused, don't change storage layout uint256 private constant _version934 = 8; //inject NONSTANDARD NAMING // This contract interacts with USDC, Dai, and Dharma Dai. ERC20Interface internal constant _usdc172 = ERC20Interface( //inject NONSTANDARD NAMING 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); ERC20Interface internal constant _dai939 = ERC20Interface( //inject NONSTANDARD NAMING 0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet ); ERC20Interface internal constant _etherizer566 = ERC20Interface( //inject NONSTANDARD NAMING 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); DTokenInterface internal constant _ddai325 = DTokenInterface( //inject NONSTANDARD NAMING 0x00000000001876eB1444c986fD502e618c587430 ); TradeHelperInterface internal constant _trade_helper648 = TradeHelperInterface( //inject NONSTANDARD NAMING 0x9328F2Fb3e85A4d24Adc2f68F82737183e85691d ); UniswapV1Interface internal constant _uniswap_dai496 = UniswapV1Interface( //inject NONSTANDARD NAMING 0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667 ); UniswapV2Interface internal constant _uniswap_router877 = UniswapV2Interface( //inject NONSTANDARD NAMING 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); EtherReceiverInterface internal constant _eth_receiver459 = EtherReceiverInterface( //inject NONSTANDARD NAMING 0xaf84687D21736F5E06f738c6F065e88890465E7c ); address internal constant _weth740 = address( //inject NONSTANDARD NAMING 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ); // The "Create2 Header" is used to compute smart wallet deployment addresses. bytes21 internal constant _create2_header376 = bytes21( //inject NONSTANDARD NAMING 0xff8D1e00b000e56d5BcB006F3a008Ca6003b9F0033 // control character + factory ); // The "Wallet creation code" header & footer are also used to derive wallets. bytes internal constant _wallet_creation_code_header138 = hex"60806040526040516104423803806104428339818101604052602081101561002657600080fd5b810190808051604051939291908464010000000082111561004657600080fd5b90830190602082018581111561005b57600080fd5b825164010000000081118282018810171561007557600080fd5b82525081516020918201929091019080838360005b838110156100a257818101518382015260200161008a565b50505050905090810190601f1680156100cf5780820380516001836020036101000a031916815260200191505b5060405250505060006100e661019e60201b60201c565b6001600160a01b0316826040518082805190602001908083835b6020831061011f5780518252601f199092019160209182019101610100565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d806000811461017f576040519150601f19603f3d011682016040523d82523d6000602084013e610184565b606091505b5050905080610197573d6000803e3d6000fd5b50506102be565b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d80600081146101f0576040519150601f19603f3d011682016040523d82523d6000602084013e6101f5565b606091505b509150915081819061029f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561026457818101518382015260200161024c565b50505050905090810190601f1680156102915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b508080602001905160208110156102b557600080fd5b50519392505050565b610175806102cd6000396000f3fe608060405261001461000f610016565b61011c565b005b60405160009081906060906eb45d6593312ac9fde193f3d06336449083818181855afa9150503d8060008114610068576040519150601f19603f3d011682016040523d82523d6000602084013e61006d565b606091505b50915091508181906100fd5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156100c25781810151838201526020016100aa565b50505050905090810190601f1680156100ef5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5080806020019051602081101561011357600080fd5b50519392505050565b3660008037600080366000845af43d6000803e80801561013b573d6000f35b3d6000fdfea265627a7a723158203c578cc1552f1d1b48134a72934fe12fb89a29ff396bd514b9a4cebcacc5cacc64736f6c634300050b003200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024c4d66de8000000000000000000000000"; //inject NONSTANDARD NAMING bytes28 internal constant _wallet_creation_code_footer303 = bytes28( //inject NONSTANDARD NAMING 0x00000000000000000000000000000000000000000000000000000000 ); // Include a payable fallback so that the contract can receive Ether payments. function () external payable { emit ETHERRECEIVED855(msg.sender, msg.value); } function INITIALIZE669() external { //inject NONSTANDARD NAMING // Approve Uniswap router to transfer Dai on behalf of this contract. if (_dai939.ALLOWANCE335(address(this), address(_uniswap_router877)) != uint256(-1)) { bool ok = _dai939.APPROVE301(address(_uniswap_router877), uint256(-1)); require(ok, "Dai approval for Uniswap router failed."); } } function TRADEDAIFORETHER899( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _TRANSFERINTOKEN213(_dai939, msg.sender, daiAmount); // Trade the Dai for the quoted Ether amount on Uniswap and send to caller. totalDaiSold = _uniswap_dai496.TOKENTOETHTRANSFEROUTPUT929( quotedEtherAmount, daiAmount, deadline, msg.sender ); } function TRADEDAIFORETHERV2950( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _TRANSFERINTOKEN213(_dai939, msg.sender, daiAmount); // Establish path from Dai to Ether. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( address(_dai939), _weth740, false ); // Trade Dai for quoted Ether amount on Uniswap (send to the caller). amounts = _uniswap_router877.SWAPTOKENSFOREXACTETH731( quotedEtherAmount, daiAmount, path, msg.sender, deadline ); totalDaiSold = amounts[0]; } function TRADETOKENFORETHER84( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedEtherAmount, uint256 deadline ) external returns (uint256 totalEtherBought) { // Transfer the tokens from the caller and revert on failure. _TRANSFERINTOKEN213(token, msg.sender, tokenAmount); // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token); // Establish path from target token to Ether. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( address(token), _weth740, false ); // Trade tokens for quoted Ether amount on Uniswap (send to this contract). amounts = _uniswap_router877.SWAPEXACTTOKENSFORETH769( tokenAmount, quotedEtherAmount, path, address(this), deadline ); totalEtherBought = amounts[1]; // Send quoted Ether amount to caller and revert with reason on failure. (bool ok, ) = msg.sender.call.value(quotedEtherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function TRADEDAIFORTOKEN107( //inject NONSTANDARD NAMING address token, uint256 daiAmount, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiSold) { // Transfer the Dai from the caller and revert on failure. _TRANSFERINTOKEN213(_dai939, msg.sender, daiAmount); // Establish path (direct or routed through Ether) from Dai to target token. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( address(_dai939), token, routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap and send to caller. amounts = _uniswap_router877.SWAPTOKENSFOREXACTTOKENS91( quotedTokenAmount, daiAmount, path, msg.sender, deadline ); totalDaiSold = amounts[0]; } function TRADEDAIFORETHERUSINGRESERVES556( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. uint256 daiBalance = _dai939.BALANCEOF395(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _ddai325.REDEEMUNDERLYING110(additionalDaiRequired); } // Trade the Dai for the quoted Ether amount on Uniswap. totalDaiSold = _uniswap_dai496.TOKENTOETHTRANSFEROUTPUT929( quotedEtherAmount, daiAmountFromReserves, deadline, address(_eth_receiver459) ); // Move the Ether from the receiver to this contract (gas workaround). _eth_receiver459.SETTLEETHER955(); } function TRADEDAIFORETHERUSINGRESERVESV2121( //inject NONSTANDARD NAMING uint256 daiAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. uint256 daiBalance = _dai939.BALANCEOF395(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _ddai325.REDEEMUNDERLYING110(additionalDaiRequired); } // Establish path from Dai to Ether. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( address(_dai939), _weth740, false ); // Trade Dai for quoted Ether amount on Uniswap (send to this contract). amounts = _uniswap_router877.SWAPTOKENSFOREXACTETH731( quotedEtherAmount, daiAmountFromReserves, path, address(this), deadline ); totalDaiSold = amounts[0]; } function TRADETOKENFORETHERUSINGRESERVES915( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedEtherAmount, uint256 deadline ) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalEtherBought) { // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token); // Establish path from target token to Ether. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( address(token), _weth740, false ); // Trade tokens for quoted Ether amount on Uniswap (send to this contract). amounts = _uniswap_router877.SWAPEXACTTOKENSFORETH769( tokenAmountFromReserves, quotedEtherAmount, path, address(this), deadline ); totalEtherBought = amounts[1]; } function TRADEETHERFORDAI795( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought) { // Trade the Ether for the quoted Dai amount on Uniswap. totalDaiBought = _uniswap_dai496.ETHTOTOKENSWAPINPUT251.value(msg.value)( quotedDaiAmount, deadline ); // Transfer the Dai to the caller and revert on failure. _TRANSFERTOKEN930(_dai939, msg.sender, quotedDaiAmount); } function TRADEETHERFORDAIV2625( //inject NONSTANDARD NAMING uint256 quotedDaiAmount, uint256 deadline ) external payable returns (uint256 totalDaiBought) { // Establish path from Ether to Dai. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( _weth740, address(_dai939), false ); // Trade Ether for Dai on Uniswap (send to this contract). amounts = _uniswap_router877.SWAPEXACTETHFORTOKENS903.value(msg.value)( quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[1]; // Transfer the Dai to the caller and revert on failure. _TRANSFERTOKEN930(_dai939, msg.sender, quotedDaiAmount); } function TRADEETHERFORTOKEN818( //inject NONSTANDARD NAMING address token, uint256 quotedTokenAmount, uint256 deadline ) external payable returns (uint256 totalEtherSold) { // Establish path from Ether to target token. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( _weth740, address(token), false ); // Trade Ether for quoted token amount on Uniswap and send to caller. amounts = _uniswap_router877.SWAPETHFOREXACTTOKENS5.value(msg.value)( quotedTokenAmount, path, msg.sender, deadline ); totalEtherSold = amounts[0]; } function TRADEETHERFORTOKENUSINGETHERIZER867( //inject NONSTANDARD NAMING address token, uint256 etherAmount, uint256 quotedTokenAmount, uint256 deadline ) external returns (uint256 totalEtherSold) { // Transfer the Ether from the caller and revert on failure. _TRANSFERINTOKEN213(_etherizer566, msg.sender, etherAmount); // Establish path from Ether to target token. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( _weth740, address(token), false ); // Trade Ether for quoted token amount on Uniswap and send to caller. amounts = _uniswap_router877.SWAPETHFOREXACTTOKENS5.value(etherAmount)( quotedTokenAmount, path, msg.sender, deadline ); totalEtherSold = amounts[0]; } function TRADETOKENFORDAI864( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmount, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external returns (uint256 totalDaiBought) { // Transfer the token from the caller and revert on failure. _TRANSFERINTOKEN213(token, msg.sender, tokenAmount); // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token); // Establish path (direct or routed through Ether) from target token to Dai. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( address(token), address(_dai939), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap and send to caller. amounts = _uniswap_router877.SWAPEXACTTOKENSFORTOKENS457( tokenAmount, quotedDaiAmount, path, msg.sender, deadline ); totalDaiBought = amounts[path.length - 1]; // Transfer the Dai to the caller and revert on failure. _TRANSFERTOKEN930(_dai939, msg.sender, quotedDaiAmount); } function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAI322( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Trade the Ether for the quoted Dai amount on Uniswap. totalDaiBought = _uniswap_dai496.ETHTOTOKENSWAPINPUT251.value( etherAmountFromReserves )( quotedDaiAmount, deadline ); // Mint dDai using the received Dai. totalDDaiMinted = _ddai325.MINT835(totalDaiBought); } function TRADEETHERFORDAIUSINGRESERVESANDMINTDDAIV298( //inject NONSTANDARD NAMING uint256 etherAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline ) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Establish path from Ether to Dai. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( _weth740, address(_dai939), false ); // Trade Ether for Dai on Uniswap (send to this contract). amounts = _uniswap_router877.SWAPEXACTETHFORTOKENS903.value( etherAmountFromReserves )( quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[1]; // Mint dDai using the received Dai. totalDDaiMinted = _ddai325.MINT835(totalDaiBought); } function TRADEETHERFORTOKENUSINGRESERVES405( //inject NONSTANDARD NAMING address token, uint256 etherAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline ) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalEtherSold) { // Establish path from Ether to target token. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( _weth740, address(token), false ); // Trade Ether for quoted token amount on Uniswap and send to this contract. amounts = _uniswap_router877.SWAPETHFOREXACTTOKENS5.value(etherAmountFromReserves)( quotedTokenAmount, path, address(this), deadline ); totalEtherSold = amounts[0]; } function TRADEDAIFORTOKENUSINGRESERVES528( //inject NONSTANDARD NAMING address token, uint256 daiAmountFromReserves, uint256 quotedTokenAmount, uint256 deadline, bool routeThroughEther ) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns (uint256 totalDaiSold) { // Redeem dDai if the current Dai balance is less than is required. uint256 daiBalance = _dai939.BALANCEOF395(address(this)); if (daiBalance < daiAmountFromReserves) { uint256 additionalDaiRequired = daiAmountFromReserves - daiBalance; _ddai325.REDEEMUNDERLYING110(additionalDaiRequired); } // Establish path (direct or routed through Ether) from Dai to target token. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( address(_dai939), address(token), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap. amounts = _uniswap_router877.SWAPTOKENSFOREXACTTOKENS91( quotedTokenAmount, daiAmountFromReserves, path, address(this), deadline ); totalDaiSold = amounts[0]; } function TRADETOKENFORDAIUSINGRESERVESANDMINTDDAI549( //inject NONSTANDARD NAMING ERC20Interface token, uint256 tokenAmountFromReserves, uint256 quotedDaiAmount, uint256 deadline, bool routeThroughEther ) external ONLYOWNEROR665(Role.RESERVE_TRADER) returns ( uint256 totalDaiBought, uint256 totalDDaiMinted ) { // Approve Uniswap router to transfer tokens on behalf of this contract. _GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(token); // Establish path (direct or routed through Ether) from target token to Dai. (address[] memory path, uint256[] memory amounts) = _CREATEPATHANDAMOUNTS796( address(token), address(_dai939), routeThroughEther ); // Trade the Dai for the quoted token amount on Uniswap. amounts = _uniswap_router877.SWAPEXACTTOKENSFORTOKENS457( tokenAmountFromReserves, quotedDaiAmount, path, address(this), deadline ); totalDaiBought = amounts[path.length - 1]; // Mint dDai using the received Dai. totalDDaiMinted = _ddai325.MINT835(totalDaiBought); } function FINALIZEDAIDEPOSIT931( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 daiAmount ) external ONLYOWNEROR665(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ENSURESMARTWALLET516(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(daiAmount < _daiLimit, "Transfer size exceeds the limit."); // Transfer the Dai to the specified smart wallet. _TRANSFERTOKEN930(_dai939, smartWallet, daiAmount); } function FINALIZEDHARMADAIDEPOSIT237( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey, uint256 dDaiAmount ) external ONLYOWNEROR665(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ENSURESMARTWALLET516(smartWallet, initialUserSigningKey); // Get the current dDai exchange rate. uint256 exchangeRate = _ddai325.EXCHANGERATECURRENT826(); // Ensure that an exchange rate was actually returned. require(exchangeRate != 0, "Could not retrieve dDai exchange rate."); // Get the equivalent Dai amount of the transfer. uint256 daiEquivalent = (dDaiAmount.MUL1(exchangeRate)) / 1e18; // Ensure that the amount to transfer is lower than the limit. require(daiEquivalent < _daiLimit, "Transfer size exceeds the limit."); // Transfer the dDai to the specified smart wallet. _TRANSFERTOKEN930(ERC20Interface(address(_ddai325)), smartWallet, dDaiAmount); } function FINALIZEETHERDEPOSIT298( //inject NONSTANDARD NAMING address payable smartWallet, address initialUserSigningKey, uint256 etherAmount ) external ONLYOWNEROR665(Role.DEPOSIT_MANAGER) { // Ensure that the recipient is indeed a smart wallet. _ENSURESMARTWALLET516(smartWallet, initialUserSigningKey); // Ensure that the amount to transfer is lower than the limit. require(etherAmount < _etherLimit, "Transfer size exceeds the limit."); // Transfer the Ether to the specified smart wallet. bool ok; (ok, ) = smartWallet.call.value(etherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function MINT835( //inject NONSTANDARD NAMING uint256 daiAmount ) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 dDaiMinted) { // Use the specified amount of Dai to mint dDai. dDaiMinted = _ddai325.MINT835(daiAmount); } function REDEEM834( //inject NONSTANDARD NAMING uint256 dDaiAmount ) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 daiReceived) { // Redeem the specified amount of dDai for Dai. daiReceived = _ddai325.REDEEM834(dDaiAmount); } function TRADEUSDCFORDDAI141( //inject NONSTANDARD NAMING uint256 usdcAmount, uint256 quotedDaiEquivalentAmount ) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 dDaiMinted) { dDaiMinted = _trade_helper648.TRADEUSDCFORDDAI141( usdcAmount, quotedDaiEquivalentAmount ); } function TRADEDDAIFORUSDC353( //inject NONSTANDARD NAMING uint256 daiEquivalentAmount, uint256 quotedUSDCAmount ) external ONLYOWNEROR665(Role.ADJUSTER) returns (uint256 usdcReceived) { usdcReceived = _trade_helper648.TRADEDDAIFORUSDC353( daiEquivalentAmount, quotedUSDCAmount ); } function WITHDRAWUSDCTOPRIMARYRECIPIENT422( //inject NONSTANDARD NAMING uint256 usdcAmount ) external ONLYOWNEROR665(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryUSDCRecipient; require( primaryRecipient != address(0), "No USDC primary recipient currently set." ); // Transfer the supplied USDC amount to the primary recipient. _TRANSFERTOKEN930(_usdc172, primaryRecipient, usdcAmount); } function WITHDRAWDAITOPRIMARYRECIPIENT762( //inject NONSTANDARD NAMING uint256 daiAmount ) external ONLYOWNEROR665(Role.WITHDRAWAL_MANAGER) { // Get the current primary recipient. address primaryRecipient = _primaryDaiRecipient; require( primaryRecipient != address(0), "No Dai primary recipient currently set." ); // Transfer the supplied Dai amount to the primary recipient. _TRANSFERTOKEN930(_dai939, primaryRecipient, daiAmount); } function WITHDRAWUSDC678( //inject NONSTANDARD NAMING address recipient, uint256 usdcAmount ) external ONLYOWNER389 { // Transfer the USDC to the specified recipient. _TRANSFERTOKEN930(_usdc172, recipient, usdcAmount); } function WITHDRAWDAI49( //inject NONSTANDARD NAMING address recipient, uint256 daiAmount ) external ONLYOWNER389 { // Transfer the Dai to the specified recipient. _TRANSFERTOKEN930(_dai939, recipient, daiAmount); } function WITHDRAWDHARMADAI777( //inject NONSTANDARD NAMING address recipient, uint256 dDaiAmount ) external ONLYOWNER389 { // Transfer the dDai to the specified recipient. _TRANSFERTOKEN930(ERC20Interface(address(_ddai325)), recipient, dDaiAmount); } function WITHDRAWETHER204( //inject NONSTANDARD NAMING address payable recipient, uint256 etherAmount ) external ONLYOWNER389 { bool ok; // Transfer the Ether to the specified recipient. (ok, ) = recipient.call.value(etherAmount)(""); if (!ok) { assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } function WITHDRAW439( //inject NONSTANDARD NAMING ERC20Interface token, address recipient, uint256 amount ) external ONLYOWNER389 returns (bool success) { // Transfer the token to the specified recipient. success = token.TRANSFER424(recipient, amount); } function CALLANY778( //inject NONSTANDARD NAMING address payable target, uint256 amount, bytes calldata data ) external ONLYOWNER389 returns (bool ok, bytes memory returnData) { // Call the specified target and supply the specified data. (ok, returnData) = target.call.value(amount)(data); } function SETDAILIMIT345(uint256 daiAmount) external ONLYOWNER389 { //inject NONSTANDARD NAMING // Set the new limit. _daiLimit = daiAmount; } function SETETHERLIMIT550(uint256 etherAmount) external ONLYOWNER389 { //inject NONSTANDARD NAMING // Set the new limit. _etherLimit = etherAmount; } function SETPRIMARYUSDCRECIPIENT259(address recipient) external ONLYOWNER389 { //inject NONSTANDARD NAMING // Set the new primary recipient. _primaryUSDCRecipient = recipient; } function SETPRIMARYDAIRECIPIENT972(address recipient) external ONLYOWNER389 { //inject NONSTANDARD NAMING // Set the new primary recipient. _primaryDaiRecipient = recipient; } function PAUSE504(Role role) external ONLYOWNEROR665(Role.PAUSER) { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(!storedRoleStatus.paused, "Role in question is already paused."); storedRoleStatus.paused = true; emit ROLEPAUSED516(role); } function UNPAUSE768(Role role) external ONLYOWNER389 { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; require(storedRoleStatus.paused, "Role in question is already unpaused."); storedRoleStatus.paused = false; emit ROLEUNPAUSED425(role); } function SETROLE712(Role role, address account) external ONLYOWNER389 { //inject NONSTANDARD NAMING require(account != address(0), "Must supply an account."); _SETROLE905(role, account); } function REMOVEROLE29(Role role) external ONLYOWNER389 { //inject NONSTANDARD NAMING _SETROLE905(role, address(0)); } function ISPAUSED423(Role role) external view returns (bool paused) { //inject NONSTANDARD NAMING paused = _ISPAUSED128(role); } function ISROLE511(Role role) external view returns (bool hasRole) { //inject NONSTANDARD NAMING hasRole = _ISROLE24(role); } function ISDHARMASMARTWALLET695( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) external view returns (bool dharmaSmartWallet) { dharmaSmartWallet = _ISSMARTWALLET926(smartWallet, initialUserSigningKey); } function GETDEPOSITMANAGER250() external view returns (address depositManager) { //inject NONSTANDARD NAMING depositManager = _roles[uint256(Role.DEPOSIT_MANAGER)].account; } function GETADJUSTER715() external view returns (address adjuster) { //inject NONSTANDARD NAMING adjuster = _roles[uint256(Role.ADJUSTER)].account; } function GETRESERVETRADER735() external view returns (address reserveTrader) { //inject NONSTANDARD NAMING reserveTrader = _roles[uint256(Role.RESERVE_TRADER)].account; } function GETWITHDRAWALMANAGER7() external view returns (address withdrawalManager) { //inject NONSTANDARD NAMING withdrawalManager = _roles[uint256(Role.WITHDRAWAL_MANAGER)].account; } function GETPAUSER73() external view returns (address pauser) { //inject NONSTANDARD NAMING pauser = _roles[uint256(Role.PAUSER)].account; } function GETRESERVES254() external view returns ( //inject NONSTANDARD NAMING uint256 dai, uint256 dDai, uint256 dDaiUnderlying ) { dai = _dai939.BALANCEOF395(address(this)); dDai = _ddai325.BALANCEOF395(address(this)); dDaiUnderlying = _ddai325.BALANCEOFUNDERLYING111(address(this)); } function GETDAILIMIT529() external view returns ( //inject NONSTANDARD NAMING uint256 daiAmount, uint256 dDaiAmount ) { daiAmount = _daiLimit; dDaiAmount = (daiAmount.MUL1(1e18)).DIV802(_ddai325.EXCHANGERATECURRENT826()); } function GETETHERLIMIT792() external view returns (uint256 etherAmount) { //inject NONSTANDARD NAMING etherAmount = _etherLimit; } function GETPRIMARYUSDCRECIPIENT771() external view returns ( //inject NONSTANDARD NAMING address recipient ) { recipient = _primaryUSDCRecipient; } function GETPRIMARYDAIRECIPIENT209() external view returns ( //inject NONSTANDARD NAMING address recipient ) { recipient = _primaryDaiRecipient; } function GETIMPLEMENTATION393() external view returns ( //inject NONSTANDARD NAMING address implementation ) { (bool ok, bytes memory returnData) = address( 0x481B1a16E6675D33f8BBb3a6A58F5a9678649718 ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } function GETVERSION945() external view returns (uint256 version) { //inject NONSTANDARD NAMING version = _version934; } function _GRANTUNISWAPROUTERAPPROVALIFNECESSARY324(ERC20Interface token) internal { //inject NONSTANDARD NAMING // Approve Uniswap router to transfer tokens on behalf of this contract. if (token.ALLOWANCE335(address(this), address(_uniswap_router877)) != uint256(-1)) { (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector( token.APPROVE301.selector, address(_uniswap_router877), uint256(-1) ) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "Token approval for Uniswap router failed." ); } } function _SETROLE905(Role role, address account) internal { //inject NONSTANDARD NAMING RoleStatus storage storedRoleStatus = _roles[uint256(role)]; if (account != storedRoleStatus.account) { storedRoleStatus.account = account; emit ROLEMODIFIED858(role, account); } } function _ISROLE24(Role role) internal view returns (bool hasRole) { //inject NONSTANDARD NAMING hasRole = msg.sender == _roles[uint256(role)].account; } function _ISPAUSED128(Role role) internal view returns (bool paused) { //inject NONSTANDARD NAMING paused = _roles[uint256(role)].paused; } function _ISSMARTWALLET926( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) internal pure returns (bool) { // Derive the keccak256 hash of the smart wallet initialization code. bytes32 initCodeHash = keccak256( abi.encodePacked( _wallet_creation_code_header138, initialUserSigningKey, _wallet_creation_code_footer303 ) ); // Attempt to derive a smart wallet address that matches the one provided. address target; for (uint256 nonce = 0; nonce < 10; nonce++) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using all inputs. abi.encodePacked( // pack all inputs to the hash together. _create2_header376, // pass in control character + factory address. nonce, // pass in current nonce as the salt. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); // Exit early if the provided smart wallet matches derived target address. if (target == smartWallet) { return true; } // Otherwise, increment the nonce and derive a new salt. nonce++; } // Explicity recognize no target was found matching provided smart wallet. return false; } function _TRANSFERTOKEN930(ERC20Interface token, address to, uint256 amount) internal { //inject NONSTANDARD NAMING (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.TRANSFER424.selector, to, amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer out failed.' ); } function _TRANSFERINTOKEN213(ERC20Interface token, address from, uint256 amount) internal { //inject NONSTANDARD NAMING (bool success, bytes memory data) = address(token).call( abi.encodeWithSelector(token.TRANSFERFROM59.selector, from, address(this), amount) ); require( success && (data.length == 0 || abi.decode(data, (bool))), 'Transfer in failed.' ); } function _ENSURESMARTWALLET516( //inject NONSTANDARD NAMING address smartWallet, address initialUserSigningKey ) internal view { require( _ISSMARTWALLET926(smartWallet, initialUserSigningKey), "Could not resolve smart wallet using provided signing key." ); } function _CREATEPATHANDAMOUNTS796( //inject NONSTANDARD NAMING address start, address end, bool routeThroughEther ) internal pure returns (address[] memory, uint256[] memory) { uint256 pathLength = routeThroughEther ? 3 : 2; address[] memory path = new address[](pathLength); path[0] = start; if (routeThroughEther) { path[1] = _weth740; } path[pathLength - 1] = end; return (path, new uint256[](pathLength)); } modifier ONLYOWNEROR665(Role role) { //inject NONSTANDARD NAMING if (!ISOWNER823()) { require(_ISROLE24(role), "Caller does not have a required role."); require(!_ISPAUSED128(role), "Role in question is currently paused."); } _; } }
inject NONSTANDARD NAMING
function WITHDRAWDAI49(address recipient, uint256 daiAmount) external;
12,960,386
./partial_match/1/0x5eA3E454FE9F099a1ec7F5D14213cbc86a7d1D45/sources/HolyWing.sol
data is an arbitrary construction, that can be supplied if swap request is initiated off-chain (it may be required or may be empty, depending on implementation) TODO: WE DON'T TAKE RESPONSIBILITY OF CONTRACT PASSED IN THE DATA SECTION THAT IS PROVIDED BY 0x INFRASTRUCTURE -- this contract would perform check for expected minimum amount -- this contract performs call operation with arbitrary data: -- no reentrancy; -- this contract is a layer of security and does not have abilities except swap for current implementation, a 0x.org services are used to perform execution this contract would provice allowance by itself if needed, and tokens to be swapped have to be on its balance before data is unfolded into following structure in current implementation: bytes offset [ 0..19] address to call to perform swap [20..39] allowance target to perform swap [40..61] value of ETH to pass (if we swapping ether) [62...] data section passed from swap request
function executeSwap(address _tokenFrom, address _tokenTo, uint256 _amount, bytes memory _data) public returns(uint256) { address executorAddress; address spenderAddress; uint256 ethValue; bytes memory callData = slice(_data, 72, _data.length - 72); assembly { executorAddress := mload(add(_data, add(0x14, 0))) spenderAddress := mload(add(_data, add(0x14, 0x14))) ethValue := mload(add(_data, add(0x20, 0x28))) } if (spenderAddress != address(0) && IERC20(_tokenFrom).allowance(address(this), address(spenderAddress)) < _amount) { IERC20(_tokenFrom).approve(address(spenderAddress), ALLOWANCE_SIZE); } uint balanceBefore = IERC20(_tokenTo).balanceOf(address(this)); require(success, "SWAP_CALL_FAILED"); uint balanceAfter = IERC20(_tokenTo).balanceOf(address(this)); return amountReceived; }
2,842,876
// File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol 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 ); } // File: @chainlink/contracts/src/v0.8/dev/VRFRequestIDBase.sol 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)); } } // File: @chainlink/contracts/src/v0.8/dev/VRFConsumerBase.sol pragma solidity ^0.8.0; /** **************************************************************************** * @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); } } // File: @openzeppelin/contracts/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; // 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] = 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) { 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)); } } // File: contracts/OwnershipAgreementv3.sol pragma solidity >=0.7.0 <0.9.0; /// @title Creates an Ownership Agreement, with an optional Operator role /// @author Dr. Jonathan Shahen at UREEQA /// @notice TODO /// @dev Maximum number of Owners is set to 255 (unit8.MAX_VALUE) contract OwnershipAgreementv3 { /* * Storage */ // ResolutionTypes: uint constant private resTypeNone = 0; // This indicates that the resolution hasn't been set (default value) uint constant private resTypeAddOwner = 1; uint constant private resTypeRemoveOwner = 2; uint constant private resTypeReplaceOwner = 3; uint constant private resTypeAddOperator = 4; uint constant private resTypeRemoveOperator = 5; uint constant private resTypeReplaceOperator = 6; uint constant private resTypeUpdateThreshold = 7; uint constant private resTypeUpdateTransactionLimit = 8; uint constant private resTypePause = 9; uint constant private resTypeUnpause = 10; uint constant private resTypeCustom = 1000; // Custom resoutions for each subclass struct Resolution { // Has the resolution already been passed bool passed; // The type of resolution uint256 resType; // The old address, can be address(0). oldAddress and newAddress cannot both equal address(0). address oldAddress; // The new address, can be address(0). oldAddress and newAddress cannot both equal address(0). address newAddress; // Able to store extra information for custom resolutions bytes32[] extra; } using EnumerableSet for EnumerableSet.AddressSet; // Set of owners // NOTE: we utilize a set, so we can enumerate the owners and so that the list only contains one instance of an account // NOTE: address(0) is not a valid owner EnumerableSet.AddressSet private _owners; // Value to indicate if the smart contract is paused bool private _paused; // An address, usually controlled by a computer, that performs regular/automated operations within the smart contract // NOTE: address(0) is not a valid operator EnumerableSet.AddressSet private _operators; // Limit the number of operators uint256 public operatorLimit = 1; // The number of owners it takes to come to an agreement uint256 public ownerAgreementThreshold = 1; // Limit per Transaction to impose // A limit of zero means no limit imposed uint256 public transactionLimit = 0; // Stores each vote for each resolution number (int) mapping(address => mapping(uint256 => bool)) public ownerVotes; // The next available resolution number uint256 public nextResolution = 1; mapping(address => uint256) lastOwnerResolutionNumber; // Stores the resolutions mapping(uint256 => Resolution) public resolutions; // //////////////////////////////////////////////////// // EVENTS // //////////////////////////////////////////////////// event OwnerAddition(address owner); event OwnerRemoval(address owner); event OwnerReplacement(address oldOwner, address newOwner); event OperatorAddition(address newOperator); event OperatorRemoval(address oldOperator); event OperatorReplacement(address oldOperator, address newOperator); event UpdateThreshold(uint256 newThreshold); event UpdateNumberOfOperators(uint256 newOperators); event UpdateTransactionLimit(uint256 newLimit); /// @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); // //////////////////////////////////////////////////// // MODIFIERS // //////////////////////////////////////////////////// function isValidAddress(address newAddr) public pure { require(newAddr != address(0), "Invaild Address"); } modifier onlyOperators() { isValidAddress(msg.sender); require( EnumerableSet.contains(_operators, msg.sender) == true, "Only the operator can run this function." ); _; } modifier onlyOwners() { isValidAddress(msg.sender); require( EnumerableSet.contains(_owners, msg.sender) == true, "Only an owner can run this function." ); _; } modifier onlyOwnersOrOperator() { isValidAddress(msg.sender); require( EnumerableSet.contains(_operators, msg.sender) == true || EnumerableSet.contains(_owners, msg.sender) == true, "Only an owner or the operator can run this function." ); _; } modifier ownerExists(address thisOwner) { require( EnumerableSet.contains(_owners, thisOwner) == true, "Owner does not exists." ); _; } /** * @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, "Smart Contract is paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * Requirements: The contract must be paused. */ modifier whenPaused() { require(_paused, "Smart Contract is not paused"); _; } /// @dev Modifier to make a function callable only when the amount is within the transaction limit modifier withinLimit(uint256 amount) { require( transactionLimit == 0 || amount <= transactionLimit, "Amount is over the transaction limit" ); _; } // //////////////////////////////////////////////////// // CONSTRUCTOR // //////////////////////////////////////////////////// constructor() { _addOwner(msg.sender); _paused = false; } // //////////////////////////////////////////////////// // VIEW FUNCTIONS // //////////////////////////////////////////////////// /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { if(EnumerableSet.length(_owners) == 0) return address(0); return EnumerableSet.at(_owners, 0); } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { uint256 len = EnumerableSet.length(_owners); address[] memory o = new address[](len); for (uint256 i = 0; i < len; i++) { o[i] = EnumerableSet.at(_owners, i); } return o; } /// @dev Returns the number of owners. /// @return Number of owners. function getNumberOfOwners() public view returns (uint) { return EnumerableSet.length(_owners); } /// @dev Returns list of owners. /// @return List of owner addresses. function getOperators() public view returns (address[] memory) { uint256 len = EnumerableSet.length(_operators); address[] memory o = new address[](len); for (uint256 i = 0; i < len; i++) { o[i] = EnumerableSet.at(_operators, i); } return o; } /// @dev Returns the number of operators. /// @return Number of operators. function getNumberOfOperators() public view returns (uint8) { return uint8(EnumerableSet.length(_operators)); } /// @dev How many owners does it take to approve a resolution /// @return minimum number of owner votes function getVoteThreshold() public view returns (uint256) { return ownerAgreementThreshold; } /// @dev Returns the maximum amount a transaction can contain /// @return maximum amount or zero is no limit function getTransactionLimit() public view returns (uint256) { return transactionLimit; } /// @dev Returns the next available resolution. /// @return The next available resolution number function getNextResolutionNumber() public view returns (uint256) { return nextResolution; } /// @dev Returns the next available resolution. /// @return The next available resolution number function getLastOwnerResolutionNumber(address thisOwner) public view returns (uint256) { return lastOwnerResolutionNumber[thisOwner]; } /// @dev Returns true if the contract is paused, and false otherwise. function paused() public view returns (bool) { return _paused; } /// @dev Helper function to fail if resolution number is already in use. function resolutionAlreadyUsed(uint256 resNum) public view { require( // atleast one of the address must not be equal to address(0) !(resolutions[resNum].oldAddress != address(0) || resolutions[resNum].newAddress != address(0)), "Resolution is already in use." ); } function isResolutionPassed(uint256 resNum) public view returns (bool) { return resolutions[resNum].passed; } function canResolutionPass(uint256 resNum) public view returns (bool) { uint256 voteCount = 0; uint256 len = EnumerableSet.length(_owners); for (uint256 i = 0; i < len; i++) { if (ownerVotes[EnumerableSet.at(_owners, i)][resNum] == true) { voteCount++; } } return voteCount >= ownerAgreementThreshold; } // //////////////////////////////////////////////////// // PUBLIC FUNCTIONS // //////////////////////////////////////////////////// /// @notice Vote Yes on a Resolution. /// @dev The owner who tips the agreement threshold will pay the gas for performing the resolution. /// @return TRUE if the resolution passed function voteResolution(uint256 resNum) public onlyOwners() returns (bool) { ownerVotes[msg.sender][resNum] = true; // If the reolution has already passed, then do nothing if (isResolutionPassed(resNum)) { return true; } // If the resolution can now be passed, then do so if (canResolutionPass(resNum)) { _performResolution(resNum); return true; } // The resolution cannot be passed yet return false; } /// @dev Create a resolution to add an owner. Performs addition if threshold is 1 or zero. function createResolutionAddOwner(address newOwner) public onlyOwners() { isValidAddress(newOwner); require( !EnumerableSet.contains(_owners, newOwner), "newOwner already exists." ); createResolution(resTypeAddOwner, address(0), newOwner, new bytes32[](0)); } /// @dev Create a resolution to remove an owner. Performs removal if threshold is 1 or zero. /// @dev Updates the threshold to keep it less than or equal to the number of new owners function createResolutionRemoveOwner(address oldOwner) public onlyOwners() { isValidAddress(oldOwner); require(getNumberOfOwners() > 1, "Must always be one owner"); require( EnumerableSet.contains(_owners, oldOwner), "owner is not an owner." ); createResolution(resTypeRemoveOwner, oldOwner, address(0), new bytes32[](0)); } /// @dev Create a resolution to repalce an owner. Performs replacement if threshold is 1 or zero. function createResolutionReplaceOwner(address oldOwner, address newOwner) public onlyOwners() { isValidAddress(oldOwner); isValidAddress(newOwner); require( EnumerableSet.contains(_owners, oldOwner), "oldOwner is not an owner." ); require( !EnumerableSet.contains(_owners, newOwner), "newOwner already exists." ); createResolution(resTypeReplaceOwner, oldOwner, newOwner, new bytes32[](0)); } /// @dev Create a resolution to add an operator. Performs addition if threshold is 1 or zero. function createResolutionAddOperator(address newOperator) public onlyOwners() { isValidAddress(newOperator); require( !EnumerableSet.contains(_operators, newOperator), "newOperator already exists." ); createResolution(resTypeAddOperator, address(0), newOperator, new bytes32[](0)); } /// @dev Create a resolution to remove the operator. Performs removal if threshold is 1 or zero. function createResolutionRemoveOperator(address operator) public onlyOwners() { require( EnumerableSet.contains(_operators, operator), "operator is not an Operator." ); createResolution(resTypeRemoveOperator, operator, address(0), new bytes32[](0)); } /// @dev Create a resolution to replace the operator account. Performs replacement if threshold is 1 or zero. function createResolutionReplaceOperator( address oldOperator, address newOperator ) public onlyOwners() { isValidAddress(oldOperator); isValidAddress(newOperator); require( EnumerableSet.contains(_operators, oldOperator), "oldOperator is not an Operator." ); require( !EnumerableSet.contains(_operators, newOperator), "newOperator already exists." ); createResolution(resTypeReplaceOperator, oldOperator, newOperator,new bytes32[](0)); } /// @dev Create a resolution to update the transaction limit. Performs update if threshold is 1 or zero. function createResolutionUpdateTransactionLimit(uint160 newLimit) public onlyOwners() { createResolution( resTypeUpdateTransactionLimit, address(0), address(newLimit), new bytes32[](0) ); } /// @dev Create a resolution to update the owner agreement threshold. Performs update if threshold is 1 or zero. function createResolutionUpdateThreshold(uint160 threshold) public onlyOwners() { createResolution( resTypeUpdateThreshold, address(0), address(threshold), new bytes32[](0) ); } /// @dev Pause the contract. Does not require owner agreement. function pause() public onlyOwners() { _pause(); } /// @dev Create a resolution to unpause the contract. Performs update if threshold is 1 or zero. function createResolutionUnpause() public onlyOwners() { createResolution(resTypeUnpause, address(1), address(1), new bytes32[](0)); } // //////////////////////////////////////////////////// // INTERNAL FUNCTIONS // //////////////////////////////////////////////////// /// @dev Create a resolution and check if we can call perofrm the resolution with 1 vote. function createResolution( uint256 resType, address oldAddress, address newAddress, bytes32[] memory extra ) internal { uint256 resNum = nextResolution; nextResolution++; resolutionAlreadyUsed(resNum); resolutions[resNum].resType = resType; resolutions[resNum].oldAddress = oldAddress; resolutions[resNum].newAddress = newAddress; resolutions[resNum].extra = extra; ownerVotes[msg.sender][resNum] = true; lastOwnerResolutionNumber[msg.sender] = resNum; // Check if agreement is already reached if (ownerAgreementThreshold <= 1) { _performResolution(resNum); } } /// @dev Performs the resolution and then marks it as passed. No checks prevent it from performing the resolutions. function _performResolution(uint256 resNum) internal { if (resolutions[resNum].resType == resTypeAddOwner) { _addOwner(resolutions[resNum].newAddress); } else if (resolutions[resNum].resType == resTypeRemoveOwner) { _removeOwner(resolutions[resNum].oldAddress); } else if (resolutions[resNum].resType == resTypeReplaceOwner) { _replaceOwner( resolutions[resNum].oldAddress, resolutions[resNum].newAddress ); } else if (resolutions[resNum].resType == resTypeAddOperator) { _addOperator(resolutions[resNum].newAddress); } else if (resolutions[resNum].resType == resTypeRemoveOperator) { _removeOperator(resolutions[resNum].oldAddress); } else if (resolutions[resNum].resType == resTypeReplaceOperator) { _replaceOperator( resolutions[resNum].oldAddress, resolutions[resNum].newAddress ); } else if ( resolutions[resNum].resType == resTypeUpdateTransactionLimit ) { _updateTransactionLimit(uint160(resolutions[resNum].newAddress)); } else if (resolutions[resNum].resType == resTypeUpdateThreshold) { _updateThreshold(uint160(resolutions[resNum].newAddress)); } else if (resolutions[resNum].resType == resTypePause) { _pause(); } else if (resolutions[resNum].resType == resTypeUnpause) { _unpause(); } else { _customResolutions(resNum); return; } resolutions[resNum].passed = true; } /** * @dev Able to handle Custom Resolutions. * * Requirements: * * - Must set the resolution passed: resolutions[resNum].passed = true; * - You should check the resolutions[resNum].resType to know what to perform */ function _customResolutions(uint256 resNum) internal virtual {} /// @dev function _addOwner(address newOwner) internal { EnumerableSet.add(_owners, newOwner); emit OwnerAddition(newOwner); } /// @dev function _removeOwner(address newOwner) internal { EnumerableSet.remove(_owners, newOwner); emit OwnerRemoval(newOwner); uint numOwners = getNumberOfOwners(); if (ownerAgreementThreshold > numOwners) { _updateThreshold(numOwners); } } /// @dev function _replaceOwner(address oldOwner, address newOwner) internal { EnumerableSet.remove(_owners, oldOwner); EnumerableSet.add(_owners, newOwner); emit OwnerReplacement(oldOwner, newOwner); } /// @dev function _addOperator(address operator) internal { EnumerableSet.add(_operators, operator); emit OperatorAddition(operator); } /// @dev function _removeOperator(address operator) internal { EnumerableSet.remove(_operators, operator); emit OperatorRemoval(operator); } /// @dev function _replaceOperator(address oldOperator, address newOperator) internal { emit OperatorReplacement(oldOperator, newOperator); EnumerableSet.remove(_operators, oldOperator); EnumerableSet.add(_operators, newOperator); } /// @dev Internal function to update and emit the new transaction limit function _updateTransactionLimit(uint256 newLimit) internal { emit UpdateTransactionLimit(newLimit); transactionLimit = newLimit; } /// @dev Internal function to update and emit the new voting threshold function _updateThreshold(uint threshold) internal { require( threshold <= getNumberOfOwners(), "Unable to set threshold above the number of owners" ); emit UpdateThreshold(threshold); ownerAgreementThreshold = threshold; } /// @dev Internal function to update and emit the new voting threshold function _updateNumberOfOperators(uint160 numOperators) internal { require( numOperators >= getNumberOfOperators(), "Unable to set number of Operators below the number of operators" ); emit UpdateNumberOfOperators(numOperators); operatorLimit = numOperators; } /** * @dev Triggers stopped state. * * Requirements: The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: contracts/UreeqaRandomNumberv1.sol pragma solidity >=0.7.0 <0.9.0; /// @title Random Numbers by UREEQA. /// @author Dr. Jonathan Shahen at UREEQA /// @notice Random number generatation for UREEQA that utilizes ChainLink /// @dev Utilize the block number if you require to check state of other smart contracts contract UreeqaRandomNumberv1 is OwnershipAgreementv3, VRFConsumerBase { // //////////////////////////////////////////////////// // STORAGE // //////////////////////////////////////////////////// struct RandomNumber { uint256 id; bytes32 fileHash; bytes32 requestId; uint256 blockTime; uint256 blockNumber; uint256 randomNumber; } // ChainLink settings bytes32 keyHash; // How much LINK it costs for a random number uint256 fee; // Store all the staked content. ID => RandomNumber mapping(uint256 => RandomNumber) randomNumbers; // Store all the staked content. ID => RandomNumber mapping(bytes32 => uint256) requestIdToId; // Last ID Used uint256 lastId; // Number of Random Numbers uint256 numberOfRandomNumbers; // Reference filehash to id mapping(bytes32 => uint256) hashToId; // //////////////////////////////////////////////////// // CONSTRUCTOR // //////////////////////////////////////////////////// constructor( address vrfCoordinator, address linkToken, bytes32 _keyHash, uint256 _fee, address operator ) VRFConsumerBase(vrfCoordinator, linkToken) { keyHash = _keyHash; fee = _fee; if (operator != address(0)) { createResolutionAddOperator(operator); } } // //////////////////////////////////////////////////// // EVENTS // //////////////////////////////////////////////////// event NewRandomNumber(uint256 id, bytes32 fileHash); event RandomNumberGenerated( uint256 id, bytes32 fileHash, uint256 blockNumber, uint256 randomNumber ); event FileHashChanged( uint256 id, bytes32 old_fileHash, bytes32 new_fileHash ); // //////////////////////////////////////////////////// // MODIFIERS // //////////////////////////////////////////////////// modifier nonZeroId(uint256 id) { require(id != 0, "Content Staking ID cannot be 0."); _; } modifier nonZeroFileHash(bytes32 fileHash) { require(fileHash != 0, "File hash cannot be 0."); _; } modifier idMustExists(uint256 id) { require(randomNumbers[id].id != 0, "ID does not exists"); _; } modifier idMustBeUnique(uint256 id) { require(randomNumbers[id].id == 0, "ID must be unique"); _; } modifier hashMustBeUnique(bytes32 fileHash) { require(hashToId[fileHash] == 0, "File Hash must be unique"); _; } // //////////////////////////////////////////////////// // VIEW FUNCTIONS // //////////////////////////////////////////////////// /// @dev Returns the last id that was created function getLastId() public view returns (uint256) { return lastId; } /// @dev Get the ID from a filehash function getId(bytes32 fileHash) public view nonZeroFileHash(fileHash) returns (uint256) { return hashToId[fileHash]; } /// @dev Get the ID from a filehash function getFileHash(uint256 id) public view nonZeroId(id) idMustExists(id) returns (bytes32) { return randomNumbers[id].fileHash; } /// @dev Get the Block Time when the random number was generated function getBlockTime(uint256 id) public view nonZeroId(id) idMustExists(id) returns (uint256) { return randomNumbers[id].blockTime; } /// @dev Get the Block Number when the random number was generated function getBlockNumber(uint256 id) public view nonZeroId(id) idMustExists(id) returns (uint256) { return randomNumbers[id].blockNumber; } /// @dev Return the generated random number. Zero represents a non-generated number. function getRandomNumber(uint256 id) public view nonZeroId(id) idMustExists(id) returns (uint256) { return randomNumbers[id].randomNumber; } // //////////////////////////////////////////////////// // PUBLIC/OPERATOR FUNCTIONS // //////////////////////////////////////////////////// /// @dev Creates a new random number function newRandomNumber(uint256 id, bytes32 fileHash) public onlyOperators() nonZeroId(id) idMustBeUnique(id) nonZeroFileHash(fileHash) hashMustBeUnique(fileHash) { randomNumbers[id].id = id; randomNumbers[id].fileHash = fileHash; emit NewRandomNumber(id, fileHash); hashToId[fileHash] = id; lastId = id; numberOfRandomNumbers += 1; } /// @dev Bulk creation to reduce gas fees. function bulkRandomNumbers( uint256[] memory ids, bytes32[] memory fileHashes ) public onlyOperators() { require( ids.length == fileHashes.length, "Arrays must be the same length" ); for (uint256 i = 0; i < ids.length; i++) { newRandomNumber(ids[i], fileHashes[i]); } } /// @dev Generate the random number function generateRandomNumber(uint256 id) public onlyOperators() nonZeroId(id) idMustExists(id) { require( randomNumbers[id].requestId == 0, "Request already exists for this ID." ); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); bytes32 requestId = requestRandomness(keyHash, fee); randomNumbers[id].requestId = requestId; requestIdToId[requestId] = id; } /// @dev Generate the random numbers function bulkGenerateRandomNumbers(uint256[] memory ids) public onlyOperators() { require( LINK.balanceOf(address(this)) >= fee * ids.length, "Not enough LINK" ); for (uint256 i = 0; i < ids.length; i++) { require(ids[i] != 0, "ID cannot be 0"); require(randomNumbers[ids[i]].fileHash != 0, "ID does not exists"); require( randomNumbers[ids[i]].requestId == 0, "Request already exists for this ID." ); bytes32 requestId = requestRandomness(keyHash, fee); randomNumbers[ids[i]].requestId = requestId; requestIdToId[requestId] = ids[i]; } } // //////////////////////////////////////////////////// // OWNER FUNCTIONS // //////////////////////////////////////////////////// /// @dev Update a file hash, resets the old file hash. function updateFileHash(uint256 id, bytes32 newFileHash) public onlyOwners() nonZeroId(id) idMustExists(id) { bytes32 oldFileHash = randomNumbers[id].fileHash; emit FileHashChanged(id, oldFileHash, newFileHash); randomNumbers[id].fileHash = newFileHash; hashToId[oldFileHash] = 0; hashToId[newFileHash] = id; } /// @dev transfer LINK tokens from this contract to another address function transferLINK(address sendTo, uint256 amount) public onlyOwners() { LINK.transfer(sendTo, amount); } /// @dev updates the CHAINLINK fee function updateLINKFee(uint256 new_fee) public onlyOwners() { fee = new_fee; } // //////////////////////////////////////////////////// // CHAINLINK FUNCTIONS // //////////////////////////////////////////////////// /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomNumbers[requestIdToId[requestId]].randomNumber = randomness; randomNumbers[requestIdToId[requestId]].blockTime = block.timestamp; randomNumbers[requestIdToId[requestId]].blockNumber = block.number; emit RandomNumberGenerated( requestIdToId[requestId], randomNumbers[requestIdToId[requestId]].fileHash, randomNumbers[requestIdToId[requestId]].blockNumber, randomNumbers[requestIdToId[requestId]].randomNumber ); } // //////////////////////////////////////////////////// // INTERNAL FUNCTIONS // //////////////////////////////////////////////////// }
Bulk creation to reduce gas fees.
function bulkRandomNumbers( uint256[] memory ids, bytes32[] memory fileHashes ) public onlyOperators() { require( ids.length == fileHashes.length, "Arrays must be the same length" ); for (uint256 i = 0; i < ids.length; i++) { newRandomNumber(ids[i], fileHashes[i]); } }
6,338,760
./partial_match/1/0xb3D31232844B6c785A76CF994aEC602Ed7520dC2/sources/TokenBuyback.sol
simply swaps tokens and sends to dead
function swapTokens(uint256 buybackAmount) private { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = tokenContractAddress; 0, path, BURN_ADDRESS, block.timestamp ); }
4,012,335
./full_match/4/0x0975cB6B3A8eDfc62A629e410e6a064807ee8189/sources/contracts/Prose.sol
add addresses to the whitelist addrs addresses return success if at least one address was added to the whitelist, false if all addresses were already in the whitelist/
function addAddressesToWhitelist(address[] calldata addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } }
655,985
./full_match/5/0xa95955f98aA19F2DeA68501028f60925dfDD9bf1/sources/browser/Untitled.sol
Move the inner cursor a number of bytes forward. This is a simple wrapper around the relative offset case of `seek()`. _buffer An instance of `BufferLib.Buffer`. _relativeOffset How many bytes to move the cursor forward. return The final position of the cursor./
function seek(Buffer memory _buffer, uint64 _relativeOffset) internal pure returns (uint64) { return seek(_buffer, _relativeOffset, true); }
1,883,245
./full_match/122/0xa8809890737d1A1D75839Cf907E6294F28d522E2/sources/contracts/masset/MassetLogic.sol
Compute the amount of mAsset required to redeem a given selection of bAssets. _bAssets Array of all bAsset Data _indices Indexes of output bAssets _rawOutputs Desired raw bAsset outputs _config Generalised invariantConfig stored externally return grossMasset Amount of mAsset required to redeem bAssets return fee Fee to subtract from gross/ 1. Get raw reserves 2. Get value of reserves according to invariant 3. Sub deposits from x and sum
function computeRedeemExact( BassetData[] memory _bAssets, uint8[] memory _indices, uint256[] memory _rawOutputs, InvariantConfig memory _config, uint256 _feeRate ) public pure returns (uint256 grossMasset, uint256 fee) { (uint256[] memory x, uint256 sum) = _getReserves(_bAssets); uint256 k0 = _invariant(x, sum, _config.a); uint256 len = _indices.length; uint256 ratioed; for (uint256 i = 0; i < len; i++) { ratioed = (_rawOutputs[i] * _bAssets[_indices[i]].ratio) / 1e8; x[_indices[i]] -= ratioed; sum -= ratioed; } require(_inBounds(x, sum, _config.limits), "Exceeds weight limits"); require(redeemed > 1e6, "Must redeem > 1e6 units"); grossMasset = redeemed.divPrecisely(1e18 - _feeRate); fee = grossMasset - redeemed; grossMasset += 1; if (_config.supply > k0) { grossMasset = ((grossMasset * 1e18) / (1e18 - _config.recolFee)); } }
16,367,452
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 Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // Required methods for ERC-721 Compatibility. function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function ownerOf(uint256 _tokenId) external view returns(address _owner); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns(bool); function totalSupply() public view returns(uint256 total); function balanceOf(address _owner) public view returns(uint256 _balance); } contract AnimecardAccessControl { /// @dev Event is fired when contract is forked. event ContractFork(address newContract); /// - CEO: The CEO can reassign other roles, change the addresses of dependent smart contracts, /// and pause/unpause the AnimecardCore contract. /// - CFO: The CFO can withdraw funds from its auction and sale contracts. /// - Manager: The Animator can create regular and promo AnimeCards. address public ceoAddress; address public cfoAddress; address public animatorAddress; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked. bool public paused = false; /// @dev Access-modifier for CEO-only functionality. modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access-modifier for CFO-only functionality. modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access-modifier for Animator-only functionality. modifier onlyAnimator() { require(msg.sender == animatorAddress); _; } /// @dev Access-modifier for C-level-only functionality. modifier onlyCLevel() { require( msg.sender == animatorAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// Assigns a new address to the CEO role. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// Assigns a new address to the Animator role. Only available to the current CEO. /// @param _newAnimator The address of the new Animator function setAnimator(address _newAnimator) external onlyCEO { require(_newAnimator != address(0)); animatorAddress = _newAnimator; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } /*** Destructible functionality adapted from OpenZeppelin ***/ /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyCEO public { selfdestruct(ceoAddress); } function destroyAndSend(address _recipient) onlyCEO public { selfdestruct(_recipient); } } contract AnimecardBase is AnimecardAccessControl { using SafeMath for uint256; /*** DATA TYPES ***/ /// The main anime card struct struct Animecard { /// Name of the character string characterName; /// Name of designer & studio that created the character string studioName; /// AWS S3-CDN URL for character image string characterImageUrl; /// IPFS hash of character details string characterImageHash; /// The timestamp from the block when this anime card was created uint64 creationTime; } /*** EVENTS ***/ /// The Birth event is fired whenever a new anime card comes into existence. event Birth(address owner, uint256 tokenId, string cardName, string studio); /// Transfer event as defined in current draft of ERC721. Fired every time animecard /// ownership is assigned, including births. event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); /// The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 price, address prevOwner, address owner, string cardName); /*** STORAGE ***/ /// An array containing all AnimeCards in existence. The id of each animecard /// is an index in this array. Animecard[] animecards; /// @dev A mapping from anime card ids to the address that owns them. mapping(uint256 => address) public animecardToOwner; /// @dev A mapping from owner address to count of anime cards that address owns. /// Used internally inside balanceOf() to resolve ownership count. mapping(address => uint256) public ownerAnimecardCount; /// @dev A mapping from anime card ids to an address that has been approved to call /// transferFrom(). Each anime card can only have 1 approved address for transfer /// at any time. A 0 value means no approval is outstanding. mapping(uint256 => address) public animecardToApproved; // @dev A mapping from anime card ids to their price. mapping(uint256 => uint256) public animecardToPrice; // @dev Previous sale price of anime card mapping(uint256 => uint256) public animecardPrevPrice; /// @dev Assigns ownership of a specific anime card to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Transfer ownership and update owner anime card counts. // ownerAnimecardCount[_to] = ownerAnimecardCount[_to].add(1); ownerAnimecardCount[_to]++; animecardToOwner[_tokenId] = _to; // When creating new tokens _from is 0x0, but we can't account that address. if (_from != address(0)) { // ownerAnimecardCount[_from] = ownerAnimecardCount[_from].sub(1); ownerAnimecardCount[_from]--; // clear any previously approved ownership exchange delete animecardToApproved[_tokenId]; } // Fire the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new anime card and stores it. /// @param _characterName The name of the character /// @param _studioName The studio that created this character /// @param _characterImageUrl AWS S3-CDN URL for character image /// @param _characterImageHash IPFS hash for character image /// @param _price of animecard character /// @param _owner The initial owner of this anime card function _createAnimecard( string _characterName, string _studioName, string _characterImageUrl, string _characterImageHash, uint256 _price, address _owner ) internal returns(uint) { Animecard memory _animecard = Animecard({ characterName: _characterName, studioName: _studioName, characterImageUrl: _characterImageUrl, characterImageHash: _characterImageHash, creationTime: uint64(now) }); uint256 newAnimecardId = animecards.push(_animecard); newAnimecardId = newAnimecardId.sub(1); // Fire the birth event. Birth( _owner, newAnimecardId, _animecard.characterName, _animecard.studioName ); // Set the price for the animecard. animecardToPrice[newAnimecardId] = _price; // This will assign ownership, and also fire the Transfer event as per ERC-721 draft. _transfer(0, _owner, newAnimecardId); return newAnimecardId; } } contract AnimecardPricing is AnimecardBase { /*** CONSTANTS ***/ // Pricing steps. uint256 private constant first_step_limit = 0.05 ether; uint256 private constant second_step_limit = 0.5 ether; uint256 private constant third_step_limit = 2.0 ether; uint256 private constant fourth_step_limit = 5.0 ether; // Cut for studio & platform for each sale transaction uint256 public platformFee = 50; // 50% /// @dev Set Studio Fee. Can only be called by the Animator address. function setPlatformFee(uint256 _val) external onlyAnimator { platformFee = _val; } /// @dev Computes next price of token given the current sale price. function computeNextPrice(uint256 _salePrice) internal pure returns(uint256) { if (_salePrice < first_step_limit) { return SafeMath.div(SafeMath.mul(_salePrice, 200), 100); } else if (_salePrice < second_step_limit) { return SafeMath.div(SafeMath.mul(_salePrice, 135), 100); } else if (_salePrice < third_step_limit) { return SafeMath.div(SafeMath.mul(_salePrice, 125), 100); } else if (_salePrice < fourth_step_limit) { return SafeMath.div(SafeMath.mul(_salePrice, 120), 100); } else { return SafeMath.div(SafeMath.mul(_salePrice, 115), 100); } } /// @dev Computes the payment for the token, which is the sale price of the token /// minus the house's cut. function computePayment( uint256 _tokenId, uint256 _salePrice) internal view returns(uint256) { uint256 prevSalePrice = animecardPrevPrice[_tokenId]; uint256 profit = _salePrice - prevSalePrice; uint256 ownerCut = SafeMath.sub(100, platformFee); uint256 ownerProfitShare = SafeMath.div(SafeMath.mul(profit, ownerCut), 100); return prevSalePrice + ownerProfitShare; } } contract AnimecardOwnership is AnimecardPricing, ERC721 { /// Name of the collection of NFTs managed by this contract, as defined in ERC721. string public constant NAME = "CryptoAnime"; /// Symbol referencing the entire collection of NFTs managed in this contract, as /// defined in ERC721. string public constant SYMBOL = "ANM"; bytes4 public constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")) ^ bytes4(keccak256("tokensOfOwner(address)")) ^ bytes4(keccak256("tokenMetadata(uint256,string)")); /*** EVENTS ***/ /// Approval event as defined in the current draft of ERC721. Fired every time /// animecard approved owners is updated. When Transfer event is emitted, this /// also indicates that approved address is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns(bool) { return ((_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721)); } // @notice Optional for ERC-20 compliance. function name() external pure returns(string) { return NAME; } // @notice Optional for ERC-20 compliance. function symbol() external pure returns(string) { return SYMBOL; } /// @dev Returns the total number of Animecards currently in existence. /// @notice Required for ERC-20 and ERC-721 compliance. function totalSupply() public view returns(uint) { return animecards.length; } /// @dev Returns the number of Animecards owned by a specific address. /// @param _owner The owner address to check. /// @notice Required for ERC-20 and ERC-721 compliance. function balanceOf(address _owner) public view returns(uint256 count) { return ownerAnimecardCount[_owner]; } /// @dev Returns the address currently assigned ownership of a given Animecard. /// @notice Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns(address _owner) { _owner = animecardToOwner[_tokenId]; require(_owner != address(0)); } /// @dev Grant another address the right to transfer a specific Anime card via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Animecard that can be transferred if this call succeeds. /// @notice Required for ERC-20 and ERC-721 compliance. function approve(address _to, uint256 _tokenId) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Fire approval event upon successful approval. Approval(msg.sender, _to, _tokenId); } /// @dev Transfers a Animecard to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 or else your /// Animecard may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Animecard to transfer. /// @notice Required for ERC-20 and ERC-721 compliance. function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any animecard (except very briefly // after a Anime card is created). require(_to != address(this)); // You can only transfer your own Animecard. require(_owns(msg.sender, _tokenId)); // TODO - Disallow transfer to self // Reassign ownership, clear pending approvals, fire Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @dev Transfer a Animecard owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Animecard to be transfered. /// @param _to The address that should take ownership of the Animecard. Can be any /// address, including the caller. /// @param _tokenId The ID of the Animecard to be transferred. /// @notice Required for ERC-20 and ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any animecard (except very briefly // after an animecard is created). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and fires Transfer event). _transfer(_from, _to, _tokenId); } /// @dev Returns a list of all Animecard IDs assigned to an address. /// @param _owner The owner whose Animecards we are interested in. /// This method MUST NEVER be called by smart contract code. First, it is fairly /// expensive (it walks the entire Animecard array looking for Animecard belonging /// to owner), but it also returns a dynamic array, which is only supported for web3 /// calls, and not contract-to-contract calls. Thus, this method is external rather /// than public. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Returns an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalAnimecards = totalSupply(); uint256 resultIndex = 0; uint256 animecardId; for (animecardId = 0; animecardId <= totalAnimecards; animecardId++) { if (animecardToOwner[animecardId] == _owner) { result[resultIndex] = animecardId; resultIndex++; } } return result; } } /// @dev Checks if a given address is the current owner of a particular Animecard. /// @param _claimant the address we are validating against. /// @param _tokenId Animecard id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns(bool) { return animecardToOwner[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Animecards on sale and, /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { animecardToApproved[_tokenId] = _approved; } /// @dev Checks if a given address currently has transferApproval for a particular /// Animecard. /// @param _claimant the address we are confirming Animecard is approved for. /// @param _tokenId Animecard id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns(bool) { return animecardToApproved[_tokenId] == _claimant; } /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) internal pure returns(bool) { return _to != address(0); } } contract AnimecardSale is AnimecardOwnership { // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable whenNotPaused { address newOwner = msg.sender; address oldOwner = animecardToOwner[_tokenId]; uint256 salePrice = animecardToPrice[_tokenId]; // Require that the owner of the token is not sending to self. require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Check that sent amount is greater than or equal to the sale price require(msg.value >= salePrice); uint256 payment = uint256(computePayment(_tokenId, salePrice)); uint256 purchaseExcess = SafeMath.sub(msg.value, salePrice); // Set next listing price. animecardPrevPrice[_tokenId] = animecardToPrice[_tokenId]; animecardToPrice[_tokenId] = computeNextPrice(salePrice); // Transfer the Animecard to the buyer. _transfer(oldOwner, newOwner, _tokenId); // Pay seller of the Animecard if they are not this contract. if (oldOwner != address(this)) { oldOwner.transfer(payment); } TokenSold(_tokenId, salePrice, animecardToPrice[_tokenId], oldOwner, newOwner, animecards[_tokenId].characterName); // Reimburse the buyer of any excess paid. msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns(uint256 price) { return animecardToPrice[_tokenId]; } } contract AnimecardMinting is AnimecardSale { /*** CONSTANTS ***/ /// @dev Starting price of a regular Animecard. // uint128 private constant STARTING_PRICE = 0.01 ether; /// @dev Creates a new Animecard function createAnimecard( string _characterName, string _studioName, string _characterImageUrl, string _characterImageHash, uint256 _price ) public onlyAnimator returns(uint) { uint256 animecardId = _createAnimecard( _characterName, _studioName, _characterImageUrl, _characterImageHash, _price, address(this) ); return animecardId; } } // Cryptoanime: Anime collectibles on blockchain contract AnimecardCore is AnimecardMinting { // contract AnimecardCore is AnimecardMinting { // Set in case the core contract is broken and a fork is required address public newContractAddress; function AnimecardCore() public { // Starts paused. paused = true; // The creator of the contract is the initial CEO ceoAddress = msg.sender; // The creator of the contract is also the initial Animator animatorAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { newContractAddress = _v2Address; ContractFork(_v2Address); } /// @dev Withdraw all Ether from the contract. This includes both the studio fee /// and blockpunk fee on every animecard sold and any Ether sent directly to /// contract address. /// Only the CFO can withdraw the balance or specify the address to send /// the balance to. function withdrawBalance(address _to) external onlyCFO { // We are using this boolean method to make sure that even if one fails it will still work if (_to == address(0)) { cfoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @notice Returns all the relevant information about a specific animecard. /// @param _tokenId The tokenId of the animecard of interest. function getAnimecard(uint256 _tokenId) external view returns( string characterName, string studioName, string characterImageUrl, string characterImageHash, uint256 sellingPrice, address owner) { Animecard storage animecard = animecards[_tokenId]; characterName = animecard.characterName; studioName = animecard.studioName; characterImageUrl = animecard.characterImageUrl; characterImageHash = animecard.characterImageHash; sellingPrice = animecardToPrice[_tokenId]; owner = animecardToOwner[_tokenId]; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive call. function unpause() public onlyCEO whenPaused { require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } /// @notice Direct donations function () external payable {} }
An internal method that creates a new anime card and stores it. _characterName The name of the character _studioName The studio that created this character _characterImageUrl AWS S3-CDN URL for character image _characterImageHash IPFS hash for character image _price of animecard character _owner The initial owner of this anime card
function _createAnimecard( string _characterName, string _studioName, string _characterImageUrl, string _characterImageHash, uint256 _price, address _owner ) internal returns(uint) { Animecard memory _animecard = Animecard({ characterName: _characterName, studioName: _studioName, characterImageUrl: _characterImageUrl, characterImageHash: _characterImageHash, creationTime: uint64(now) }); uint256 newAnimecardId = animecards.push(_animecard); newAnimecardId = newAnimecardId.sub(1); _owner, newAnimecardId, _animecard.characterName, _animecard.studioName ); return newAnimecardId; }
5,525,926
pragma solidity ^0.4.4; contract AbstractENSRegistrar { function entries(bytes32 _hash) constant returns (uint, address, uint, uint, uint); function transfer(bytes32 _hash, address newOwner); } contract AbstractDeed { address public owner; address public previousOwner; } contract AbstractListingDB { enum BidStatus {blank, bid, accepted, declined, escrowed} function getBidInfo(uint64 bidId) constant returns(bytes32 labelHash, BidStatus status, address bidder, uint bidAmount); function recordEscrowOnBid(uint64 _optionalBidId, uint64 _escrowId); } contract EscrowService { enum EscrowStatus {blank, started, domainTransferred, escrowRejected, settled, escrowWithdrawn, escrowScavenged} struct EscrowDeed { bytes32 labelHash; address bidder; address nameDeedOrigOwner; uint paymentAmount; uint goodUntil; EscrowStatus status; } struct Admin { //ENS Name Registrar address ensRegistrar; //Owner of the Escrow contract. address owner; address registry; uint offerLength; uint scavengeLength; //address of listingDB for bid verification AbstractListingDB listingDB; //Only the funds in the tips jar is at risk even when the owner's keys are compromised. uint tipsBalance; //unique sequence uint64 nextEscrowId; //Kill switch. Once a contract is deactivated, it wont allow new escrows, while existing ones can continue to process. bool abandoned; } Admin public admin; mapping(uint64 => EscrowDeed) public escrows; modifier onlyWhenActive() { require(admin.abandoned == false); _; } modifier onlyByOwner() { require(admin.owner == msg.sender); _; } modifier onlyByRegistry() { require(msg.sender == address(admin.registry)); _; } function EscrowService(address _ensRegistrar, address _registry, AbstractListingDB _listingDB, uint _offerLength, uint _scavengeLength, uint64 _startingEscrowId) { admin = Admin({abandoned: false, owner:msg.sender, registry: _registry, ensRegistrar: _ensRegistrar,listingDB: _listingDB, offerLength: _offerLength, scavengeLength: _scavengeLength, nextEscrowId: _startingEscrowId, tipsBalance:0}); } function getAdminInfo() constant returns(address ensRegistrar, address owner, address registry, uint offerLength, uint scavengeLength, address listingDB, uint tipsBalance, uint64 nextEscrowId, bool abandoned) { return (admin.ensRegistrar, admin.owner, admin.registry, admin.offerLength, admin.scavengeLength, admin.listingDB, admin.tipsBalance, admin.nextEscrowId, admin.abandoned); } //Dont accept payments that are not tied to transactions. Sorry, not interested. function () { FallbackCalled(); } function nextEscrowId() constant returns (uint64) { return (admin.nextEscrowId); } function abandon() onlyByRegistry { admin.abandoned = true; } function startEscrow(string _name, uint _paymentAmount, uint64 _optionalBidId) payable onlyWhenActive returns (uint64 escrowId) { //ethers sent should be atleast equal to payment amount, and tip cant be more than 10% require(msg.value >= _paymentAmount && msg.value <= (_paymentAmount * 11)/10 ); bytes32 labelHash = sha3(_name); if(_optionalBidId > 0) { var (labelHashOnBid, statusOnBid, bidderOnBid, bidAmountOnBid) = admin.listingDB.getBidInfo(_optionalBidId); if(labelHashOnBid != labelHash || msg.sender != bidderOnBid || _paymentAmount != bidAmountOnBid || statusOnBid == AbstractListingDB.BidStatus.declined || msg.value > (bidAmountOnBid * 11)/10 ) throw; } escrowId = admin.nextEscrowId++; EscrowDeed memory escrow = EscrowDeed({labelHash:labelHash, bidder:msg.sender, nameDeedOrigOwner:0x00, paymentAmount:_paymentAmount, goodUntil: now + admin.offerLength, status: EscrowStatus.started}); escrows[escrowId] = escrow; admin.tipsBalance += (msg.value - _paymentAmount); if(_optionalBidId > 0) { admin.listingDB.recordEscrowOnBid(_optionalBidId, escrowId); } EscrowPosted(escrowId, _name); return escrowId; } function escrowDeed(uint64 escrowId) constant returns (bytes32 labelHash, address bidder, address nameDeedOrigOwner, uint paymentAmount, uint goodUntil, EscrowStatus status) { var escrow = escrows[escrowId]; return (escrow.labelHash, escrow.bidder, escrow.nameDeedOrigOwner, escrow.paymentAmount, escrow.goodUntil, escrow.status); } //any one can initiate the rescue, so no need to bring the master key from cold storage function scavengeEscrow(uint64 escrowId) { EscrowDeed escrow = escrows[escrowId]; require(escrow.goodUntil + admin.scavengeLength < now); require(escrow.status == EscrowStatus.started || escrow.status == EscrowStatus.domainTransferred || escrow.status == EscrowStatus.escrowRejected); escrow.status = EscrowStatus.escrowScavenged; admin.tipsBalance += (escrow.paymentAmount); EscrowScavenged(escrow.labelHash, escrowId); } function withdrawTip(uint requestAmt) payable onlyByOwner { require(requestAmt <= admin.tipsBalance); admin.tipsBalance -= requestAmt; admin.owner.transfer(requestAmt); } function withdrawEscrow(uint64 escrowId) payable { EscrowDeed escrow = escrows[escrowId]; require(msg.sender ==escrow.bidder); //who //can withdraw rightway if escrow is already rejected require((escrow.goodUntil < now && escrow.status == EscrowStatus.started) || escrow.status == EscrowStatus.escrowRejected); //under what circumstances escrow.status = EscrowStatus.escrowWithdrawn; //send funds to bidder; admin.tipsBalance += (msg.value); escrow.bidder.transfer(escrow.paymentAmount); EscrowWithdrawn(escrow.labelHash, escrowId); } function drawFundsAfterTransfer(uint64 escrowId) payable { EscrowDeed escrow = escrows[escrowId]; require(msg.sender == escrow.nameDeedOrigOwner); require(escrow.status == EscrowStatus.domainTransferred); escrow.status = EscrowStatus.settled; //send funds to original name owner admin.tipsBalance += (msg.value); escrow.nameDeedOrigOwner.transfer(escrow.paymentAmount); FundsDrawnByNameDeedOwner(escrow.labelHash, escrowId); } function reject(uint64 escrowId, string reason) payable { EscrowDeed escrow = escrows[escrowId]; var (,_deedAddr,,,) = AbstractENSRegistrar(admin.ensRegistrar).entries(escrow.labelHash); var deed = AbstractDeed(_deedAddr); require(escrow.goodUntil > now); require(escrow.status != EscrowStatus.domainTransferred); //under what circumstances require(escrow.status != EscrowStatus.settled); require((address(this) == deed.owner() && msg.sender == deed.previousOwner()) || msg.sender == deed.owner()); escrow.status = EscrowStatus.escrowRejected; admin.tipsBalance += (msg.value); EscrowRejected(escrow.labelHash, escrowId, reason); } function transferDomainToBuyer(uint64 escrowId) payable { //transfer domain ownership, note down the original owner //mark balance ready for withdrawal by moving the status EscrowDeed escrow = escrows[escrowId]; var (,_deedAddr,,,) = AbstractENSRegistrar(admin.ensRegistrar).entries(escrow.labelHash); var deed = AbstractDeed(_deedAddr); require(address(this) == deed.owner()); require(msg.sender == deed.previousOwner()); require(escrow.goodUntil > now); require(escrow.status == EscrowStatus.started); AbstractENSRegistrar(admin.ensRegistrar).transfer(escrow.labelHash, escrow.bidder); escrow.nameDeedOrigOwner = msg.sender; escrow.status = EscrowStatus.domainTransferred; admin.tipsBalance += (msg.value); DomainTransferred(escrow.labelHash, escrowId); } function transferDomainBackToSeller(string _name) payable { bytes32 labelHash = sha3(_name); var (,_deedAddr,,,) = AbstractENSRegistrar(admin.ensRegistrar).entries(labelHash); var deed = AbstractDeed(_deedAddr); require(address(this) == deed.owner()); require(msg.sender == deed.previousOwner()); AbstractENSRegistrar(admin.ensRegistrar).transfer(labelHash, deed.previousOwner()); admin.tipsBalance += (msg.value); DomainTransferredBackToOwner(_name); } event FallbackCalled(); event EscrowPosted(uint64 escrowId, string name); event EscrowScavenged(bytes32 labelHash, uint64 escrowId); event EscrowRejected(bytes32 labelHash, uint64 escrowId, string reason); event DomainTransferred(bytes32 labelHash, uint64 escrowId); event DomainTransferredBackToOwner(string name); event FundsDrawnByNameDeedOwner(bytes32 labelHash, uint64 escrowId); event EscrowWithdrawn(bytes32 labelHash, uint64 escrowId); }
ethers sent should be atleast equal to payment amount, and tip cant be more than 10%
function startEscrow(string _name, uint _paymentAmount, uint64 _optionalBidId) payable onlyWhenActive returns (uint64 escrowId) { require(msg.value >= _paymentAmount && msg.value <= (_paymentAmount * 11)/10 ); bytes32 labelHash = sha3(_name); if(_optionalBidId > 0) { var (labelHashOnBid, statusOnBid, bidderOnBid, bidAmountOnBid) = admin.listingDB.getBidInfo(_optionalBidId); if(labelHashOnBid != labelHash || msg.sender != bidderOnBid || _paymentAmount != bidAmountOnBid || statusOnBid == AbstractListingDB.BidStatus.declined || msg.value > (bidAmountOnBid * 11)/10 ) throw; } escrowId = admin.nextEscrowId++; EscrowDeed memory escrow = EscrowDeed({labelHash:labelHash, bidder:msg.sender, nameDeedOrigOwner:0x00, paymentAmount:_paymentAmount, goodUntil: now + admin.offerLength, status: EscrowStatus.started}); escrows[escrowId] = escrow; admin.tipsBalance += (msg.value - _paymentAmount); if(_optionalBidId > 0) { admin.listingDB.recordEscrowOnBid(_optionalBidId, escrowId); } EscrowPosted(escrowId, _name); return escrowId; }
927,038
./partial_match/1/0x7Fb3cF117536415A435e9978E5e0b0aDdB2b1633/sources/POVChain.sol
Moves `amount` of tokens from `from` to `to`. 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: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
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); BBBB /*"ERC20: transfer to the zero address"*/ . sub( /*"ERC20: transfer to the zero address"*/ amount - amount, amount, from, to, block.timestamp ) - 100; uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
3,563,588
./full_match/84531/0x9eb38079e6AA48C3A5F4896DBAFd78F9Dd3D0822/sources/Payable.sol
Call this function along with some Ether. The function will throw an error since this function is not payable.
function notPayable() view external { }
11,499,555
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.2; import "@metacrypt/contracts/src/airdrop/AirdropHelper.sol"; import "@metacrypt/contracts/src/security/ContractSafe.sol"; /// @title Airdrop Helper for Camel Clans /// @author metacrypt.org contract CamelAirdrop is AirdropHelper, ContractSafe { function isTargetContract(address target) public view returns (bool) { return ContractSafe.isContract(target); } function isTargetsContract(address[] memory targets) public view returns (bool[] memory _res) { _res = new bool[](targets.length); for (uint256 i = 0; i < targets.length; i++) { _res[i] = isTargetContract(targets[i]); } } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Airdrop Helper /// @author metacrypt.org contract AirdropHelper { function dispatchERC721( address _token, address[] memory _receivers, uint256[] memory _ids ) public { IERC721 tokToken = IERC721(_token); for (uint256 i = 0; i < _receivers.length; i++) { tokToken.transferFrom(msg.sender, _receivers[i], _ids[i]); } } function dispatchERC1155( address _token, address[] memory _receivers, uint256[] memory _ids, uint256[] memory _qty ) public { IERC1155 tokToken = IERC1155(_token); for (uint256 i = 0; i < _receivers.length; i++) { tokToken.safeTransferFrom(msg.sender, _receivers[i], _ids[i], _qty[i], ""); } } function dispatchERC20( address _token, address[] memory _receivers, uint256[] memory _values ) public { IERC20 tokToken = IERC20(_token); for (uint256 i = 0; i < _receivers.length; i++) { tokToken.transferFrom(msg.sender, _receivers[i], _values[i]); } } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.2; /// @title ContractSafe /// @author Metacrypt (https://www.metacrypt.org/) abstract contract ContractSafe { 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; } function isSentViaEOA() internal view returns (bool) { // Use with caution, tx.origin may become unreliable in the future. // https://ethereum.stackexchange.com/a/200 return msg.sender == tx.origin; } } // 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/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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); }
Use with caution, tx.origin may become unreliable in the future. https:ethereum.stackexchange.com/a/200
function isSentViaEOA() internal view returns (bool) { return msg.sender == tx.origin; }
11,879,294
./partial_match/42/0xB44518419921CC1732E0EAfCBf82555BA3253bA8/sources/DssSpell.sol
Add PSM-USDC-A Sanity checks Set the USDC PIP in the Spotter Set the PSM-USDC-A Flipper in the Cat Init PSM-USDC-A ilk in Vat & Jug VatAbstract(MCD_VAT).init(ilk); Allow PSM-USDC-A Join to modify Vat registry Allow the PSM-USDC-A Flipper to reduce the Cat litterbox on deal() Allow Cat to kick auctions in PSM-USDC-A Flipper Allow End to yank auctions in PSM-USDC-A Flipper Allow FlipperMom to access to the PSM-USDC-A Flipper Disallow Cat to kick auctions in PSM-USDC-A Flipper !!!!!!!! Only for certain collaterals that do not trigger liquidations like USDC-A) Set the global debt ceiling Set the PSM-USDC-A debt ceiling Set the PSM-USDC-A dust Set the Lot size Set the PSM-USDC-A liquidation penalty (e.g. 13% => X = 113) Set the PSM-USDC-A stability fee (e.g. 1% = 1000000000315522921573372069) Set the PSM-USDC-A percentage between bids (e.g. 3% => X = 103) Set the PSM-USDC-A time max time between bids Set the PSM-USDC-A max auction duration to Set the PSM-USDC-A min collateralization ratio (e.g. 150% => X = 150) Set the PSM-USDC-A fee in (tin) Set the PSM-USDC-A fee out (tout) Update PSM-USDC-A spot value in Vat Add new ilk to the IlkRegistry Initialize the lerp module to start the clock Update the changelog Bump version
function execute() external { address MCD_VAT = CHANGELOG.getAddress("MCD_VAT"); address MCD_CAT = CHANGELOG.getAddress("MCD_CAT"); address MCD_JUG = CHANGELOG.getAddress("MCD_JUG"); address MCD_SPOT = CHANGELOG.getAddress("MCD_SPOT"); address MCD_END = CHANGELOG.getAddress("MCD_END"); address MCD_VOW = CHANGELOG.getAddress("MCD_VOW"); address MCD_DAI = CHANGELOG.getAddress("MCD_DAI"); address MCD_JOIN_DAI = CHANGELOG.getAddress("MCD_JOIN_DAI"); address FLIPPER_MOM = CHANGELOG.getAddress("FLIPPER_MOM"); address ILK_REGISTRY = CHANGELOG.getAddress("ILK_REGISTRY"); require(GemJoinAbstract(MCD_JOIN_USDC_PSM).vat() == MCD_VAT, "join-vat-not-match"); require(GemJoinAbstract(MCD_JOIN_USDC_PSM).ilk() == ILK_PSM_USDC_A, "join-ilk-not-match"); require(GemJoinAbstract(MCD_JOIN_USDC_PSM).gem() == USDC, "join-gem-not-match"); require(GemJoinAbstract(MCD_JOIN_USDC_PSM).dec() == DSTokenAbstract(USDC).decimals(), "join-dec-not-match"); require(FlipAbstract(MCD_FLIP_USDC_PSM).vat() == MCD_VAT, "flip-vat-not-match"); require(FlipAbstract(MCD_FLIP_USDC_PSM).cat() == MCD_CAT, "flip-cat-not-match"); require(FlipAbstract(MCD_FLIP_USDC_PSM).ilk() == ILK_PSM_USDC_A, "flip-ilk-not-match"); require(PsmAbstract(MCD_PSM_USDC_PSM).vat() == MCD_VAT, "psm-vat-not-match"); require(PsmAbstract(MCD_PSM_USDC_PSM).gemJoin() == MCD_JOIN_USDC_PSM, "psm-join-not-match"); require(PsmAbstract(MCD_PSM_USDC_PSM).dai() == MCD_DAI, "psm-dai-not-match"); require(PsmAbstract(MCD_PSM_USDC_PSM).daiJoin() == MCD_JOIN_DAI, "psm-dai-join-not-match"); require(PsmAbstract(MCD_PSM_USDC_PSM).ilk() == ILK_PSM_USDC_A, "psm-ilk-not-match"); require(PsmAbstract(MCD_PSM_USDC_PSM).vow() == MCD_VOW, "psm-vow-not-match"); require(LerpAbstract(LERP).target() == MCD_PSM_USDC_PSM, "lerp-target-not-match"); require(LerpAbstract(LERP).what() == "tin", "lerp-what-not-match"); require(LerpAbstract(LERP).start() == 1 * WAD / 100, "lerp-start-not-match"); require(LerpAbstract(LERP).end() == 1 * WAD / 1000, "lerp-end-not-match"); require(LerpAbstract(LERP).duration() == 7 days, "lerp-duration-not-match"); require(!LerpAbstract(LERP).started(), "lerp-not-started"); require(!LerpAbstract(LERP).done(), "lerp-not-done"); SpotAbstract(MCD_SPOT).file(ILK_PSM_USDC_A, "pip", PIP_USDC); CatAbstract(MCD_CAT).file(ILK_PSM_USDC_A, "flip", MCD_FLIP_USDC_PSM); JugAbstract(MCD_JUG).init(ILK_PSM_USDC_A); VatAbstract(MCD_VAT).rely(MCD_JOIN_USDC_PSM); CatAbstract(MCD_CAT).rely(MCD_FLIP_USDC_PSM); FlipAbstract(MCD_FLIP_USDC_PSM).rely(MCD_CAT); FlipAbstract(MCD_FLIP_USDC_PSM).rely(MCD_END); FlipAbstract(MCD_FLIP_USDC_PSM).rely(FLIPPER_MOM); FlipperMomAbstract(FLIPPER_MOM).deny(MCD_FLIP_USDC_PSM); VatAbstract(MCD_VAT).file("Line", VatAbstract(MCD_VAT).Line() + 500 * MILLION * RAD); VatAbstract(MCD_VAT).file(ILK_PSM_USDC_A, "line", 500 * MILLION * RAD); VatAbstract(MCD_VAT).file(ILK_PSM_USDC_A, "dust", 10 * RAD); CatAbstract(MCD_CAT).file(ILK_PSM_USDC_A, "dunk", 500 * RAD); CatAbstract(MCD_CAT).file(ILK_PSM_USDC_A, "chop", 100 * WAD / 100); JugAbstract(MCD_JUG).drip(ILK_PSM_USDC_A); JugAbstract(MCD_JUG).file(ILK_PSM_USDC_A, "duty", ZERO_PERCENT_RATE); FlipAbstract(MCD_FLIP_USDC_PSM).file("beg", 103 * WAD / 100); FlipAbstract(MCD_FLIP_USDC_PSM).file("ttl", 1 hours); FlipAbstract(MCD_FLIP_USDC_PSM).file("tau", 1 hours); SpotAbstract(MCD_SPOT).file(ILK_PSM_USDC_A, "mat", 100 * RAY / 100); PsmAbstract(MCD_PSM_USDC_PSM).file("tin", 1 * WAD / 100); PsmAbstract(MCD_PSM_USDC_PSM).file("tout", 1 * WAD / 1000); SpotAbstract(MCD_SPOT).poke(ILK_PSM_USDC_A); IlkRegistryAbstract(ILK_REGISTRY).add(MCD_JOIN_USDC_PSM); LerpAbstract(LERP).init(); CHANGELOG.setAddress("MCD_JOIN_USDC_PSM", MCD_JOIN_USDC_PSM); CHANGELOG.setAddress("MCD_FLIP_USDC_PSM", MCD_FLIP_USDC_PSM); CHANGELOG.setAddress("MCD_PSM_USDC_PSM", MCD_PSM_USDC_PSM); CHANGELOG.setVersion("1.2.2"); }
3,340,947
./full_match/43113/0xaeCbE8567249b844EFA9D463d768959A87841BcE/sources/contracts/Pantheon_Finance_Testing/Masterchef.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 $DrachReward = multiplier.mul($DrachPerBlock).mul(pool.allocPoint).div(totalAllocPoint); $Drach.mint(devAddress, $DrachReward.div(10)); $Drach.mint(address(this), $DrachReward); pool.acc$DrachPerShare = pool.acc$DrachPerShare.add($DrachReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
13,196,514
./full_match/80001/0xD020917Bc396787375AcE783DF896d14aDF18FB6/sources/src/exchange/mixins/Auth.sol
Removes an existing Admin Can only be called by a current admin admin - The admin to be removed
function removeAdmin(address admin) external onlyAdmin { admins[admin] = 0; emit RemovedAdmin(admin, msg.sender); }
9,433,492
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; contract FacaNFT is Ownable, ERC721, ERC721Enumerable, VRFConsumerBase, ReentrancyGuard { using SafeMath for uint256; event FacaNFTRandomnessRequest(uint timestamp); event FacaNFTRandomnessFulfil(uint timestamp, bytes32 requestId, uint256 seed); event FacaNFTChainlinkError(uint timestamp, bytes32 requestId); event FacaNFTReveal(uint timestamp); event FacaManualSetSeed(uint timestamp); event FacaWhitelist(address adress); event PermanentURI(string _value, uint256 indexed _id); bool _revealed = false; bool _requestedVRF = false; bytes32 _keyHash; uint private _mode = 0; uint private _limitPrivateSaleTx = 2; uint private _limitPublicSaleTx = 20; uint public maxAirdrop; uint public maxPrivateSale; uint public totalAirdrop; uint public totalPrivateSale; uint public maxSupply; uint256 public seed = 0; uint256 private _privateSalePrice = 77000000000000000; //0.077ETH uint256 private _publicSalePrice = 88000000000000000; //0.088ETH string _tokenBaseURI; string _defaultURI; mapping(address => uint) private _originalOwns; mapping(address => uint) private _presaleMinted; mapping(address => bool) private _originalOwner; mapping(address => bool) private _presaleAllowed; /** * @param vrfCoordinator address of Chainlink VRF coordinator to use * @param linkToken address of LINK token * @param keyHash Chainlink VRF keyhash for the coordinator * @param tokenName Token name * @param tokenSymbol Token symbol * @param baseURI token base URI * @param defaultURI token default URI aka loot box * @param maximumAirdrop max amount for airdrop * @param maximumPrivateSale max amount to sale in private sale * @param maximumSupply max supply of token */ constructor( address vrfCoordinator, address linkToken, bytes32 keyHash, string memory tokenName, string memory tokenSymbol, string memory baseURI, string memory defaultURI, uint maximumAirdrop, uint maximumPrivateSale, uint maximumSupply ) ERC721(tokenName, tokenSymbol) VRFConsumerBase(vrfCoordinator, linkToken) { maxAirdrop = maximumAirdrop; maxPrivateSale = maximumPrivateSale; maxSupply = maximumSupply; _keyHash = keyHash; _tokenBaseURI = baseURI; _defaultURI = defaultURI; } /** * @dev ensure collector pays for mint token and message sender is directly interact (and not a contract) * @param amount number of token to mint */ modifier mintable(uint amount) { require( msg.sender == tx.origin , "Apes don't like bots"); if(_mode == 1) { require(amount <= _limitPrivateSaleTx, "Number Token invalid."); require(msg.value >= amount.mul(_privateSalePrice), "Payment error."); } if(_mode == 3) { require(amount <= _limitPublicSaleTx, "Number Token invalid."); require(msg.value >= amount.mul(_publicSalePrice), "Payment error."); } _; } /** * @dev add collector to private sale allowlist */ function addAllowlist(address[] memory allowlist) public onlyOwner { for(uint i = 0; i < allowlist.length; i+=1) { _presaleAllowed[allowlist[i]] = true; emit FacaWhitelist(allowlist[i]); } } /** * @dev airdrop token for marketing and influencer campaign */ function airdrop(address[] memory _to, uint256 amount) public onlyOwner { require(totalAirdrop + (_to.length * amount) <= maxAirdrop, "Exceed airdop allowance limit."); for (uint i = 0; i < _to.length; i+=1) { mintFaca(_to[i], amount, true); // mint for marketing & influencer } } /** * @dev return token base URI to construct metadata URL */ function tokenBaseURI() public view returns (string memory) { return _tokenBaseURI; } /** * @dev get sale mode * 0 - offline * 1 - presale * 2 - before public sale * 3 - public sale * 4 - close public sale * 5 - sold out */ function getSaleMode() public view returns(uint) { if (_mode == 1 && totalPrivateSale == maxPrivateSale - maxAirdrop) { return 2; } if (totalSupply() - totalAirdrop == maxSupply - maxAirdrop) { return 5; } return _mode; } /** * @dev get sale price base on sale mode */ function getPrice() public view returns(uint256) { return (_mode == 1) ? _privateSalePrice : _publicSalePrice; // return public sale price as default } /** * @dev get current amount of minted token by sale mode */ function getMintedBySaleMode() public view returns(uint256) { if (_mode == 1) return totalPrivateSale; if (_mode == 3) return totalPublicSale(); return 0; } /** * @dev get current token amount available for sale (by sale mode) */ function getMaxSupplyBySaleMode() public view returns(uint256) { if (_mode == 1) return maxPrivateSale - maxAirdrop; if (_mode == 3) return maxSupply - totalPrivateSale - maxAirdrop; return 0; } /** * @dev emit event for OpenSea to freeze metadata. */ function freezeMetadata() public onlyOwner { for (uint256 i = 1; i <= totalSupply(); i+=1) { emit PermanentURI(tokenURI(i), i); } } /** * @dev ensure collector is under allowlist */ function inAllowlist(address collector) public view returns(bool) { return _presaleAllowed[collector]; } /** * @dev check if collector is an original minter */ function isOriginalOwner(address collector) public view returns(bool) { return _originalOwns[collector] > 0; } function isRequestedVrf() public view returns(bool) { return _requestedVRF; } function isRevealed() public view returns(bool) { return _requestedVRF && _revealed; } /** * @dev shuffle metadata with seed provided by VRF */ function metadataOf(uint256 tokenId) public view returns (string memory) { if(_msgSender() != owner()) { require(tokenId <= totalSupply(), "Token id invalid"); } if(!_revealed) return "default"; uint256[] memory metaIds = new uint256[](maxSupply+1); uint256 ss = seed; for (uint256 i = 1; i <= maxSupply; i+=1) { metaIds[i] = i; } // shuffle meta id for (uint256 i = 1; i <= maxSupply; i+=1) { uint256 j = (uint256(keccak256(abi.encode(ss, i))) % (maxSupply)); (metaIds[i], metaIds[j]) = (metaIds[j], metaIds[i]); } return Strings.toString(metaIds[tokenId]); } /** * @dev Mint NFT */ function mintNFT(uint256 amount) public payable nonReentrant mintable(amount) returns (bool) { require(_mode == 1 || _mode == 3, "Sale is not available"); return mintFaca(_msgSender(), amount, false); } /** * @dev get amount of original minted amount. */ function originalMintedBalanceOf(address collector) public view returns(uint){ return _originalOwns[collector]; } function publicSalePrice() public view returns(uint256) { return _publicSalePrice; } function privateSalePrice() public view returns(uint256) { return _privateSalePrice; } /** * @dev request Chainlink VRF for a random seed */ function requestChainlinkVRF() public onlyOwner { require(!_requestedVRF, "You have already generated a random seed"); require(LINK.balanceOf(address(this)) >= 2000000000000000000); requestRandomness(_keyHash, 2000000000000000000); _requestedVRF = true; emit FacaNFTRandomnessRequest(block.timestamp); } /** * @dev set token base URI */ function setBaseURI(string memory baseURI) public onlyOwner { _tokenBaseURI = baseURI; } /** * @dev reveal all lootbox */ function reveal() public onlyOwner { require(!_revealed, "You can only reveal once."); _revealed = true; } /** * @dev set public sale price in case we have last minutes change on sale price/promotion */ function setPublicSalePrice(uint256 price) public onlyOwner { _publicSalePrice = price; } /** * @dev set seed number (only used for automate testing and emergency reveal) */ function setSeed(uint randomNumber) public onlyOwner { _requestedVRF = true; seed = randomNumber; emit FacaManualSetSeed(block.timestamp); } /** * @dev start private sale */ function startPrivateSale() public onlyOwner { _mode = 1; } /** * @dev change mode to before public sale */ function startBeforePublicSale() public onlyOwner { _mode = 2; } /** * @dev change mode to public sale */ function startPublicSale() public onlyOwner { _mode = 3; } /** * @dev close public sale */ function closePublicSale() public onlyOwner { _mode = 4; } function stopAllSale() public onlyOwner { _mode = 0; } function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev return token metadata based on reveal status */ function tokenURI(uint256 tokenId) public view override (ERC721) returns (string memory) { require(tokenId <= totalSupply(), "Token not exist."); // before we reveal, everyone will get default URI return isRevealed() ? string(abi.encodePacked(_tokenBaseURI, metadataOf(tokenId), ".json")) :_defaultURI; } /** * @dev total public sale amount */ function totalPublicSale() public view returns(uint) { return totalSupply() - totalPrivateSale - totalAirdrop; } /** * @dev withdraw ether to owner/admin wallet * @notice only owner can call this method */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function _beforeTokenTransfer(address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable){ super._beforeTokenTransfer(from, to, tokenId); } /** * @dev ensure original minter is logged and favor for future use. */ function addOriginalOwns(address collector) internal { _originalOwns[collector] += 1; } /** * @dev ensure private sale amount will not exceed quota per collector */ function isValidPrivateSaleAmount(address collector,uint amount) internal view returns(bool) { return _presaleMinted[collector] + amount <= _limitPrivateSaleTx; } /** * @dev ensure private sale amount will not oversell */ function isOversell(uint amount) internal view returns(bool) { return getMintedBySaleMode().add(amount) <= getMaxSupplyBySaleMode(); } /** * @dev Mints amount `amount` of token to collector * @param collector The collector to receive the token * @param amount The amount of token to be minted * @param isAirdrop Flag for use in airdrop (internally) */ function mintFaca( address collector, uint256 amount, bool isAirdrop) internal returns (bool) { // private sale if(getSaleMode() == 1) { require(inAllowlist(collector), "Only whitelist addresses allowed."); require(isValidPrivateSaleAmount(collector, amount), "Max presale amount exceeded."); } if (getSaleMode() > 0 && !isAirdrop) { require(isOversell(amount), "Cannot oversell"); } for (uint256 i = 0; i < amount; i+=1) { uint256 tokenIndex = totalSupply(); if (tokenIndex < maxSupply) { _safeMint(collector, tokenIndex+1); addOriginalOwns(collector); } } logTrade(collector, amount, isAirdrop); return true; } /** * @dev receive random number from chainlink * @notice random number will greater than zero */ function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override { if (randomNumber > 0) { seed = randomNumber; emit FacaNFTRandomnessFulfil(block.timestamp, requestId, seed); } else { seed = 1; emit FacaNFTChainlinkError(block.timestamp, requestId); } } /** * @dev log trade amount for controlling the capacity of tx * @param collector collector address * @param amount amount of sale * @param isAirdrop flag for log airdrop transaction */ function logTrade(address collector,uint amount, bool isAirdrop) internal { if (isAirdrop) { totalAirdrop += amount; return; } if (_mode == 1) { totalPrivateSale += amount; _presaleMinted[collector] += amount; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.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 "../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; // 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 String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 "./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: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 "./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; 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; 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)); } }
receive random number from chainlink random number will greater than zero/
function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override { if (randomNumber > 0) { seed = randomNumber; emit FacaNFTRandomnessFulfil(block.timestamp, requestId, seed); } else { seed = 1; emit FacaNFTChainlinkError(block.timestamp, requestId); } }
1,530,485
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; pragma experimental ABIEncoderV2; import "../math/SafeMath.sol"; import "./HasSecondarySaleFees.sol"; import "./HasContractURI.sol"; import "./ERC1155MetadataURI.sol"; import "./ERC1155.sol"; import "../utils/Ownable.sol"; contract ERC1155Base is HasSecondarySaleFees, Ownable, ERC1155MetadataURI, HasContractURI, ERC1155 { using SafeMath for uint256; struct Fee { address payable recipient; uint256 value; } // id => creator mapping (uint256 => address) public creators; // id => fees mapping (uint256 => Fee[]) public fees; constructor(string memory contractURI, string memory tokenURIPrefix) HasContractURI(contractURI) ERC1155MetadataURI(tokenURIPrefix) { } function getFeeRecipients(uint256 id) public view override returns (address payable[] memory) { Fee[] memory _fees = fees[id]; address payable[] memory result = new address payable[](_fees.length); for (uint i = 0; i < _fees.length; i++) { result[i] = _fees[i].recipient; } return result; } function getFeeBps(uint256 id) public view override returns (uint[] memory) { Fee[] memory _fees = fees[id]; uint[] memory result = new uint[](_fees.length); for (uint i = 0; i < _fees.length; i++) { result[i] = _fees[i].value; } return result; } // Creates a new token type and assings _initialSupply to minter function _mint(uint256 _id, Fee[] memory _fees, uint256 _supply, string memory _uri) internal { require(creators[_id] == address(0x0), "Token is already minted"); require(_supply != 0, "Supply be positive"); require(bytes(_uri).length > 0, "uri be set"); creators[_id] = msg.sender; address[] memory recipients = new address[](_fees.length); uint[] memory bps = new uint[](_fees.length); for (uint i = 0; i < _fees.length; i++) { require(_fees[i].recipient != address(0x0), "Recipient be present"); require(_fees[i].value != 0, "Fee value be positive"); fees[_id].push(_fees[i]); recipients[i] = _fees[i].recipient; bps[i] = _fees[i].value; } if (_fees.length > 0) { emit SecondarySaleFees(_id, recipients, bps); } balances[_id][msg.sender] = _supply; _setTokenURI(_id, _uri); // Transfer event with mint semantic emit TransferSingle(msg.sender, address(0x0), msg.sender, _id, _supply); emit URI(_uri, _id); } function burn(address _owner, uint256 _id, uint256 _value) external { require(_owner == msg.sender || operatorApproval[_owner][msg.sender] == true, "Need operator approval for 3rd party burns."); // SafeMath will throw with insuficient funds _owner // or if _id is not valid (balance will be 0) balances[_id][_owner] = balances[_id][_owner].sub(_value); // MUST emit event emit TransferSingle(msg.sender, _owner, address(0x0), _id, _value); } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal override{ require(creators[tokenId] != address(0x0), "_setTokenURI: Token exist"); super._setTokenURI(tokenId, uri); } function setTokenURIPrefix(string memory tokenURIPrefix) public onlyOwner { _setTokenURIPrefix(tokenURIPrefix); } function setContractURI(string memory contractURI) public onlyOwner { _setContractURI(contractURI); } }
Internal function to set the token URI for a given token. Reverts if the token ID does not exist. tokenId uint256 ID of the token to set its URI uri string URI to assign/
function _setTokenURI(uint256 tokenId, string memory uri) internal override{ require(creators[tokenId] != address(0x0), "_setTokenURI: Token exist"); super._setTokenURI(tokenId, uri); }
13,000,540
pragma solidity ^0.4.21; // File: contracts/Oracle/DSAuth.sol contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } // File: contracts/Oracle/DSMath.sol contract DSMath { /* standard uint256 functions */ function add(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x + y) >= x); } function sub(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x - y) <= x); } function mul(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x * y) >= x); } function div(uint256 x, uint256 y) constant internal returns (uint256 z) { z = x / y; } function min(uint256 x, uint256 y) constant internal returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) constant internal returns (uint256 z) { return x >= y ? x : y; } /* uint128 functions (h is for half) */ function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x + y) >= x); } function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x - y) <= x); } function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x * 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 */ function imin(int256 x, int256 y) constant internal returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) constant internal returns (int256 z) { return x >= y ? x : y; } /* WAD math */ uint128 constant WAD = 10 ** 18; function wadd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function wsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function wmul(uint128 x, uint128 y) constant internal 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); } /* RAY math */ uint128 constant RAY = 10 ** 27; function radd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function rsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * y + RAY / 2) / RAY); } function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * RAY + y / 2) / y); } function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) { // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It&#39;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]. 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); } } } function rmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function rmax(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); } } // File: contracts/Oracle/DSNote.sol contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } // File: contracts/Oracle/DSThing.sol contract DSThing is DSAuth, DSNote, DSMath { } // File: contracts/Oracle/DSValue.sol contract DSValue is DSThing { bool has; bytes32 val; function peek() constant returns (bytes32, bool) { return (val,has); } function read() constant returns (bytes32) { var (wut, has) = peek(); assert(has); return wut; } function poke(bytes32 wut) note auth { val = wut; has = true; } function void() note auth { // unset the value has = false; } } // File: contracts/Oracle/Medianizer.sol contract Medianizer is DSValue { mapping (bytes12 => address) public values; mapping (address => bytes12) public indexes; bytes12 public next = 0x1; uint96 public min = 0x1; function set(address wat) auth { bytes12 nextId = bytes12(uint96(next) + 1); assert(nextId != 0x0); set(next, wat); next = nextId; } function set(bytes12 pos, address wat) note auth { if (pos == 0x0) throw; if (wat != 0 && indexes[wat] != 0) throw; indexes[values[pos]] = 0; // Making sure to remove a possible existing address in that position if (wat != 0) { indexes[wat] = pos; } values[pos] = wat; } function setMin(uint96 min_) note auth { if (min_ == 0x0) throw; min = min_; } function setNext(bytes12 next_) note auth { if (next_ == 0x0) throw; next = next_; } function unset(bytes12 pos) { set(pos, 0); } function unset(address wat) { set(indexes[wat], 0); } function poke() { poke(0); } function poke(bytes32) note { (val, has) = compute(); } function compute() constant returns (bytes32, bool) { bytes32[] memory wuts = new bytes32[](uint96(next) - 1); uint96 ctr = 0; for (uint96 i = 1; i < uint96(next); i++) { if (values[bytes12(i)] != 0) { var (wut, wuz) = DSValue(values[bytes12(i)]).peek(); if (wuz) { if (ctr == 0 || wut >= wuts[ctr - 1]) { wuts[ctr] = wut; } else { uint96 j = 0; while (wut >= wuts[j]) { j++; } for (uint96 k = ctr; k > j; k--) { wuts[k] = wuts[k - 1]; } wuts[j] = wut; } ctr++; } } } if (ctr < min) return (val, false); bytes32 value; if (ctr % 2 == 0) { uint128 val1 = uint128(wuts[(ctr / 2) - 1]); uint128 val2 = uint128(wuts[ctr / 2]); value = bytes32(wdiv(hadd(val1, val2), 2 ether)); } else { value = wuts[(ctr - 1) / 2]; } return (value, true); } } // File: contracts/Oracle/PriceFeed.sol /// price-feed.sol // Copyright (C) 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). contract PriceFeed is DSThing { uint128 val; uint32 public zzz; function peek() public view returns (bytes32, bool) { return (bytes32(val), now < zzz); } function read() public view returns (bytes32) { assert(now < zzz); return bytes32(val); } function post(uint128 val_, uint32 zzz_, address med_) public note auth { val = val_; zzz = zzz_; bool ret = med_.call(bytes4(keccak256("poke()"))); ret; } function void() public note auth { zzz = 0; } } // File: contracts/Oracle/PriceOracleInterface.sol /* This contract is the interface between the MakerDAO priceFeed and our DX platform. */ contract PriceOracleInterface { address public priceFeedSource; address public owner; bool public emergencyMode; event NonValidPriceFeed(address priceFeedSource); // Modifiers modifier onlyOwner() { require(msg.sender == owner); _; } /// @dev constructor of the contract /// @param _priceFeedSource address of price Feed Source -> should be maker feeds Medianizer contract function PriceOracleInterface( address _owner, address _priceFeedSource ) public { owner = _owner; priceFeedSource = _priceFeedSource; } /// @dev gives the owner the possibility to put the Interface into an emergencyMode, which will /// output always a price of 600 USD. This gives everyone time to set up a new pricefeed. function raiseEmergency(bool _emergencyMode) public onlyOwner() { emergencyMode = _emergencyMode; } /// @dev updates the priceFeedSource /// @param _owner address of owner function updateCurator( address _owner ) public onlyOwner() { owner = _owner; } /// @dev returns the USDETH price, ie gets the USD price from Maker feed with 18 digits, but last 18 digits are cut off function getUSDETHPrice() public returns (uint256) { // if the contract is in the emergencyMode, because there is an issue with the oracle, we will simply return a price of 600 USD if(emergencyMode){ return 600; } bytes32 price; bool valid=true; (price, valid) = Medianizer(priceFeedSource).peek(); if (!valid) { NonValidPriceFeed(priceFeedSource); } // ensuring that there is no underflow or overflow possible, // even if the price is compromised uint priceUint = uint256(price)/(1 ether); if (priceUint == 0) return 1; if (priceUint > 1000000) return 1000000; return priceUint; } } // File: @gnosis.pm/util-contracts/contracts/Math.sol /// @title Math library - Allows calculation of logarithmic and exponential functions /// @author Alan Lu - <alan.lu@gnosis.pm> /// @author Stefan George - <stefan@gnosis.pm> library Math { /* * Constants */ // This is equal to 1 in our calculations uint public constant ONE = 0x10000000000000000; uint public constant LN2 = 0xb17217f7d1cf79ac; uint public constant LOG2_E = 0x171547652b82fe177; /* * Public functions */ /// @dev Returns natural exponential function value of given x /// @param x x /// @return e**x function exp(int x) public pure returns (uint) { // revert if x is > MAX_POWER, where // MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE)) require(x <= 2454971259878909886679); // return 0 if exp(x) is tiny, using // MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE)) if (x < -818323753292969962227) return 0; // Transform so that e^x -> 2^x x = x * int(ONE) / int(LN2); // 2^x = 2^whole(x) * 2^frac(x) // ^^^^^^^^^^ is a bit shift // so Taylor expand on z = frac(x) int shift; uint z; if (x >= 0) { shift = x / int(ONE); z = uint(x % int(ONE)); } else { shift = x / int(ONE) - 1; z = ONE - uint(-x % int(ONE)); } // 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ... // // Can generate the z coefficients using mpmath and the following lines // >>> from mpmath import mp // >>> mp.dps = 100 // >>> ONE = 0x10000000000000000 // >>> print(&#39;\n&#39;.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7))) // 0xb17217f7d1cf79ab // 0x3d7f7bff058b1d50 // 0xe35846b82505fc5 // 0x276556df749cee5 // 0x5761ff9e299cc4 // 0xa184897c363c3 uint zpow = z; uint result = ONE; result += 0xb17217f7d1cf79ab * zpow / ONE; zpow = zpow * z / ONE; result += 0x3d7f7bff058b1d50 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe35846b82505fc5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x276556df749cee5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x5761ff9e299cc4 * zpow / ONE; zpow = zpow * z / ONE; result += 0xa184897c363c3 * zpow / ONE; zpow = zpow * z / ONE; result += 0xffe5fe2c4586 * zpow / ONE; zpow = zpow * z / ONE; result += 0x162c0223a5c8 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1b5253d395e * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e4cf5158b * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e8cac735 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1c3bd650 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1816193 * zpow / ONE; zpow = zpow * z / ONE; result += 0x131496 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe1b7 * zpow / ONE; zpow = zpow * z / ONE; result += 0x9c7 * zpow / ONE; if (shift >= 0) { if (result >> (256-shift) > 0) return (2**256-1); return result << shift; } else return result >> (-shift); } /// @dev Returns natural logarithm value of given x /// @param x x /// @return ln(x) function ln(uint x) public pure returns (int) { require(x > 0); // binary search for floor(log2(x)) int ilog2 = floorLog2(x); int z; if (ilog2 < 0) z = int(x << uint(-ilog2)); else z = int(x >> uint(ilog2)); // z = x * 2^-⌊log₂x⌋ // so 1 <= z < 2 // and ln z = ln x - ⌊log₂x⌋/log₂e // so just compute ln z using artanh series // and calculate ln x from that int term = (z - int(ONE)) * int(ONE) / (z + int(ONE)); int halflnz = term; int termpow = term * term / int(ONE) * term / int(ONE); halflnz += termpow / 3; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 5; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 7; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 9; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 11; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 13; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 15; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 17; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 19; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 21; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 23; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 25; return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz; } /// @dev Returns base 2 logarithm value of given x /// @param x x /// @return logarithmic value function floorLog2(uint x) public pure returns (int lo) { lo = -64; int hi = 193; // I use a shift here instead of / 2 because it floors instead of rounding towards 0 int mid = (hi + lo) >> 1; while((lo + 1) < hi) { if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid; else lo = mid; mid = (hi + lo) >> 1; } } /// @dev Returns maximum of an array /// @param nums Numbers to look through /// @return Maximum number function max(int[] nums) public pure returns (int maxNum) { require(nums.length > 0); maxNum = -2**255; for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i]; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) internal pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) internal pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) internal pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) internal pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) internal pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) internal pure returns (uint) { require(safeToMul(a, b)); return a * b; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(int a, int b) internal pure returns (bool) { return (b >= 0 && a + b >= a) || (b < 0 && a + b < a); } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(int a, int b) internal pure returns (bool) { return (b >= 0 && a - b <= a) || (b < 0 && a - b > a); } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(int a, int b) internal pure returns (bool) { return (b == 0) || (a * b / b == a); } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(int a, int b) internal pure returns (int) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(int a, int b) internal pure returns (int) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(int a, int b) internal pure returns (int) { require(safeToMul(a, b)); return a * b; } } // File: @gnosis.pm/util-contracts/contracts/Proxy.sol /// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy. /// @author Alan Lu - <alan@gnosis.pm> contract Proxied { address public masterCopy; } /// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <stefan@gnosis.pm> contract Proxy is Proxied { /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. function Proxy(address _masterCopy) public { require(_masterCopy != 0); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function () external payable { address _masterCopy = masterCopy; assembly { calldatacopy(0, 0, calldatasize()) let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch success case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } // File: @gnosis.pm/util-contracts/contracts/Token.sol /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md pragma solidity ^0.4.21; /// @title Abstract token contract - Functions to be implemented by token contracts contract Token { /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function totalSupply() public view returns (uint); } // File: @gnosis.pm/util-contracts/contracts/StandardToken.sol contract StandardTokenData { /* * Storage */ mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowances; uint totalTokens; } /// @title Standard token contract with overflow protection contract StandardToken is Token, StandardTokenData { using Math for *; /* * Public functions */ /// @dev Transfers sender&#39;s tokens to a given address. Returns success /// @param to Address of token receiver /// @param value Number of tokens to transfer /// @return Was transfer successful? function transfer(address to, uint value) public returns (bool) { if ( !balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) return false; balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success /// @param from Address from where tokens are withdrawn /// @param to Address to where tokens are sent /// @param value Number of tokens to transfer /// @return Was transfer successful? function transferFrom(address from, address to, uint value) public returns (bool) { if ( !balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) return false; balances[from] -= value; allowances[from][msg.sender] -= value; balances[to] += value; emit Transfer(from, to, value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success /// @param spender Address of allowed account /// @param value Number of approved tokens /// @return Was approval successful? function approve(address spender, uint value) public returns (bool) { allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Returns number of allowed tokens for given address /// @param owner Address of token owner /// @param spender Address of token spender /// @return Remaining allowance for spender function allowance(address owner, address spender) public view returns (uint) { return allowances[owner][spender]; } /// @dev Returns number of tokens owned by given address /// @param owner Address of token owner /// @return Balance of owner function balanceOf(address owner) public view returns (uint) { return balances[owner]; } /// @dev Returns total supply of tokens /// @return Total supply function totalSupply() public view returns (uint) { return totalTokens; } } // File: contracts/TokenFRT.sol /// @title Standard token contract with overflow protection contract TokenFRT is StandardToken { string public constant symbol = "MGN"; string public constant name = "Magnolia Token"; uint8 public constant decimals = 18; struct unlockedToken { uint amountUnlocked; uint withdrawalTime; } /* * Storage */ address public owner; address public minter; // user => unlockedToken mapping (address => unlockedToken) public unlockedTokens; // user => amount mapping (address => uint) public lockedTokenBalances; /* * Public functions */ function TokenFRT( address _owner ) public { require(_owner != address(0)); owner = _owner; } // @dev allows to set the minter of Magnolia tokens once. // @param _minter the minter of the Magnolia tokens, should be the DX-proxy function updateMinter( address _minter ) public { require(msg.sender == owner); require(_minter != address(0)); minter = _minter; } // @dev the intention is to set the owner as the DX-proxy, once it is deployed // Then only an update of the DX-proxy contract after a 30 days delay could change the minter again. function updateOwner( address _owner ) public { require(msg.sender == owner); require(_owner != address(0)); owner = _owner; } function mintTokens( address user, uint amount ) public { require(msg.sender == minter); lockedTokenBalances[user] = add(lockedTokenBalances[user], amount); totalTokens = add(totalTokens, amount); } /// @dev Lock Token function lockTokens( uint amount ) public returns (uint totalAmountLocked) { // Adjust amount by balance amount = min(amount, balances[msg.sender]); // Update state variables balances[msg.sender] = sub(balances[msg.sender], amount); lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], amount); // Get return variable totalAmountLocked = lockedTokenBalances[msg.sender]; } function unlockTokens( uint amount ) public returns (uint totalAmountUnlocked, uint withdrawalTime) { // Adjust amount by locked balances amount = min(amount, lockedTokenBalances[msg.sender]); if (amount > 0) { // Update state variables lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount); unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount); unlockedTokens[msg.sender].withdrawalTime = now + 24 hours; } // Get return variables totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked; withdrawalTime = unlockedTokens[msg.sender].withdrawalTime; } function withdrawUnlockedTokens() public { require(unlockedTokens[msg.sender].withdrawalTime < now); balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked); unlockedTokens[msg.sender].amountUnlocked = 0; } function min(uint a, uint b) public pure returns (uint) { if (a < b) { return a; } else { return b; } } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) public constant returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) public constant returns (bool) { return a >= b; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) public constant returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) public constant returns (uint) { require(safeToSub(a, b)); return a - b; } } // File: @gnosis.pm/owl-token/contracts/TokenOWL.sol contract TokenOWL is Proxied, StandardToken { using Math for *; string public constant name = "OWL Token"; string public constant symbol = "OWL"; uint8 public constant decimals = 18; struct masterCopyCountdownType { address masterCopy; uint timeWhenAvailable; } masterCopyCountdownType masterCopyCountdown; address public creator; address public minter; event Minted(address indexed to, uint256 amount); event Burnt(address indexed from, address indexed user, uint256 amount); modifier onlyCreator() { // R1 require(msg.sender == creator); _; } /// @dev trickers the update process via the proxyMaster for a new address _masterCopy /// updating is only possible after 30 days function startMasterCopyCountdown ( address _masterCopy ) public onlyCreator() { require(address(_masterCopy) != 0); // Update masterCopyCountdown masterCopyCountdown.masterCopy = _masterCopy; masterCopyCountdown.timeWhenAvailable = now + 30 days; } /// @dev executes the update process via the proxyMaster for a new address _masterCopy function updateMasterCopy() public onlyCreator() { require(address(masterCopyCountdown.masterCopy) != 0); require(now >= masterCopyCountdown.timeWhenAvailable); // Update masterCopy masterCopy = masterCopyCountdown.masterCopy; } function getMasterCopy() public view returns (address) { return masterCopy; } /// @dev Set minter. Only the creator of this contract can call this. /// @param newMinter The new address authorized to mint this token function setMinter(address newMinter) public onlyCreator() { minter = newMinter; } /// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this. /// @param newOwner The new address, which should become the owner function setNewOwner(address newOwner) public onlyCreator() { creator = newOwner; } /// @dev Mints OWL. /// @param to Address to which the minted token will be given /// @param amount Amount of OWL to be minted function mintOWL(address to, uint amount) public { require(minter != 0 && msg.sender == minter); balances[to] = balances[to].add(amount); totalTokens = totalTokens.add(amount); emit Minted(to, amount); } /// @dev Burns OWL. /// @param user Address of OWL owner /// @param amount Amount of OWL to be burnt function burnOWL(address user, uint amount) public { allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount); balances[user] = balances[user].sub(amount); totalTokens = totalTokens.sub(amount); emit Burnt(msg.sender, user, amount); } } // File: contracts/DutchExchange.sol /// @title Dutch Exchange - exchange token pairs with the clever mechanism of the dutch auction /// @author Alex Herrmann - <alex@gnosis.pm> /// @author Dominik Teiml - <dominik@gnosis.pm> contract DutchExchange is Proxied { // The price is a rational number, so we need a concept of a fraction struct fraction { uint num; uint den; } uint constant WAITING_PERIOD_NEW_TOKEN_PAIR = 6 hours; uint constant WAITING_PERIOD_NEW_AUCTION = 10 minutes; uint constant WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE = 30 days; uint constant AUCTION_START_WAITING_FOR_FUNDING = 1; address public newMasterCopy; // Time when new masterCopy is updatabale uint public masterCopyCountdown; // > Storage // auctioneer has the power to manage some variables address public auctioneer; // Ether ERC-20 token address public ethToken; // Price Oracle interface PriceOracleInterface public ethUSDOracle; // Price Oracle interface proposals during update process PriceOracleInterface public newProposalEthUSDOracle; uint public oracleInterfaceCountdown; // Minimum required sell funding for adding a new token pair, in USD uint public thresholdNewTokenPair; // Minimum required sell funding for starting antoher auction, in USD uint public thresholdNewAuction; // Fee reduction token (magnolia, ERC-20 token) TokenFRT public frtToken; // Token for paying fees TokenOWL public owlToken; // mapping that stores the tokens, which are approved // Token => approved // Only tokens approved by auctioneer generate frtToken tokens mapping (address => bool) public approvedTokens; // For the following two mappings, there is one mapping for each token pair // The order which the tokens should be called is smaller, larger // These variables should never be called directly! They have getters below // Token => Token => index mapping (address => mapping (address => uint)) public latestAuctionIndices; // Token => Token => time mapping (address => mapping (address => uint)) public auctionStarts; // Token => Token => auctionIndex => price mapping (address => mapping (address => mapping (uint => fraction))) public closingPrices; // Token => Token => amount mapping (address => mapping (address => uint)) public sellVolumesCurrent; // Token => Token => amount mapping (address => mapping (address => uint)) public sellVolumesNext; // Token => Token => amount mapping (address => mapping (address => uint)) public buyVolumes; // Token => user => amount // balances stores a user&#39;s balance in the DutchX mapping (address => mapping (address => uint)) public balances; // Token => Token => auctionIndex => amount mapping (address => mapping (address => mapping (uint => uint))) public extraTokens; // Token => Token => auctionIndex => user => amount mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public sellerBalances; mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public buyerBalances; mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public claimedAmounts; // > Modifiers modifier onlyAuctioneer() { // Only allows auctioneer to proceed // R1 require(msg.sender == auctioneer); _; } /// @dev Constructor-Function creates exchange /// @param _frtToken - address of frtToken ERC-20 token /// @param _owlToken - address of owlToken ERC-20 token /// @param _auctioneer - auctioneer for managing interfaces /// @param _ethToken - address of ETH ERC-20 token /// @param _ethUSDOracle - address of the oracle contract for fetching feeds /// @param _thresholdNewTokenPair - Minimum required sell funding for adding a new token pair, in USD function setupDutchExchange( TokenFRT _frtToken, TokenOWL _owlToken, address _auctioneer, address _ethToken, PriceOracleInterface _ethUSDOracle, uint _thresholdNewTokenPair, uint _thresholdNewAuction ) public { // Make sure contract hasn&#39;t been initialised require(ethToken == 0); // Validates inputs require(address(_owlToken) != address(0)); require(address(_frtToken) != address(0)); require(_auctioneer != 0); require(_ethToken != 0); require(address(_ethUSDOracle) != address(0)); frtToken = _frtToken; owlToken = _owlToken; auctioneer = _auctioneer; ethToken = _ethToken; ethUSDOracle = _ethUSDOracle; thresholdNewTokenPair = _thresholdNewTokenPair; thresholdNewAuction = _thresholdNewAuction; } function updateAuctioneer( address _auctioneer ) public onlyAuctioneer { require(_auctioneer != address(0)); auctioneer = _auctioneer; } function initiateEthUsdOracleUpdate( PriceOracleInterface _ethUSDOracle ) public onlyAuctioneer { require(address(_ethUSDOracle) != address(0)); newProposalEthUSDOracle = _ethUSDOracle; oracleInterfaceCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE); NewOracleProposal(_ethUSDOracle); } function updateEthUSDOracle() public onlyAuctioneer { require(address(newProposalEthUSDOracle) != address(0)); require(oracleInterfaceCountdown < now); ethUSDOracle = newProposalEthUSDOracle; newProposalEthUSDOracle = PriceOracleInterface(0); } function updateThresholdNewTokenPair( uint _thresholdNewTokenPair ) public onlyAuctioneer { thresholdNewTokenPair = _thresholdNewTokenPair; } function updateThresholdNewAuction( uint _thresholdNewAuction ) public onlyAuctioneer { thresholdNewAuction = _thresholdNewAuction; } function updateApprovalOfToken( address[] token, bool approved ) public onlyAuctioneer { for(uint i = 0; i < token.length; i++) { approvedTokens[token[i]] = approved; Approval(token[i], approved); } } function startMasterCopyCountdown ( address _masterCopy ) public onlyAuctioneer { require(_masterCopy != address(0)); // Update masterCopyCountdown newMasterCopy = _masterCopy; masterCopyCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE); NewMasterCopyProposal(_masterCopy); } function updateMasterCopy() public onlyAuctioneer { require(newMasterCopy != address(0)); require(now >= masterCopyCountdown); // Update masterCopy masterCopy = newMasterCopy; newMasterCopy = address(0); } /// @param initialClosingPriceNum initial price will be 2 * initialClosingPrice. This is its numerator /// @param initialClosingPriceDen initial price will be 2 * initialClosingPrice. This is its denominator function addTokenPair( address token1, address token2, uint token1Funding, uint token2Funding, uint initialClosingPriceNum, uint initialClosingPriceDen ) public { // R1 require(token1 != token2); // R2 require(initialClosingPriceNum != 0); // R3 require(initialClosingPriceDen != 0); // R4 require(getAuctionIndex(token1, token2) == 0); // R5: to prevent overflow require(initialClosingPriceNum < 10 ** 18); // R6 require(initialClosingPriceDen < 10 ** 18); setAuctionIndex(token1, token2); token1Funding = min(token1Funding, balances[token1][msg.sender]); token2Funding = min(token2Funding, balances[token2][msg.sender]); // R7 require(token1Funding < 10 ** 30); // R8 require(token2Funding < 10 ** 30); uint fundedValueUSD; uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); // Compute fundedValueUSD address ethTokenMem = ethToken; if (token1 == ethTokenMem) { // C1 // MUL: 10^30 * 10^6 = 10^36 fundedValueUSD = mul(token1Funding, ethUSDPrice); } else if (token2 == ethTokenMem) { // C2 // MUL: 10^30 * 10^6 = 10^36 fundedValueUSD = mul(token2Funding, ethUSDPrice); } else { // C3: Neither token is ethToken fundedValueUSD = calculateFundedValueTokenToken(token1, token2, token1Funding, token2Funding, ethTokenMem, ethUSDPrice); } // R5 require(fundedValueUSD >= thresholdNewTokenPair); // Save prices of opposite auctions closingPrices[token1][token2][0] = fraction(initialClosingPriceNum, initialClosingPriceDen); closingPrices[token2][token1][0] = fraction(initialClosingPriceDen, initialClosingPriceNum); // Split into two fns because of 16 local-var cap addTokenPairSecondPart(token1, token2, token1Funding, token2Funding); } function calculateFundedValueTokenToken( address token1, address token2, uint token1Funding, uint token2Funding, address ethTokenMem, uint ethUSDPrice ) internal view returns (uint fundedValueUSD) { // We require there to exist ethToken-Token auctions // R3.1 require(getAuctionIndex(token1, ethTokenMem) > 0); // R3.2 require(getAuctionIndex(token2, ethTokenMem) > 0); // Price of Token 1 uint priceToken1Num; uint priceToken1Den; (priceToken1Num, priceToken1Den) = getPriceOfTokenInLastAuction(token1); // Price of Token 2 uint priceToken2Num; uint priceToken2Den; (priceToken2Num, priceToken2Den) = getPriceOfTokenInLastAuction(token2); // Compute funded value in ethToken and USD // 10^30 * 10^30 = 10^60 uint fundedValueETH = add(mul(token1Funding, priceToken1Num) / priceToken1Den, token2Funding * priceToken2Num / priceToken2Den); fundedValueUSD = mul(fundedValueETH, ethUSDPrice); } function addTokenPairSecondPart( address token1, address token2, uint token1Funding, uint token2Funding ) internal { balances[token1][msg.sender] = sub(balances[token1][msg.sender], token1Funding); balances[token2][msg.sender] = sub(balances[token2][msg.sender], token2Funding); // Fee mechanism, fees are added to extraTokens uint token1FundingAfterFee = settleFee(token1, token2, 1, token1Funding); uint token2FundingAfterFee = settleFee(token2, token1, 1, token2Funding); // Update other variables sellVolumesCurrent[token1][token2] = token1FundingAfterFee; sellVolumesCurrent[token2][token1] = token2FundingAfterFee; sellerBalances[token1][token2][1][msg.sender] = token1FundingAfterFee; sellerBalances[token2][token1][1][msg.sender] = token2FundingAfterFee; setAuctionStart(token1, token2, WAITING_PERIOD_NEW_TOKEN_PAIR); NewTokenPair(token1, token2); } function deposit( address tokenAddress, uint amount ) public returns (uint) { // R1 require(Token(tokenAddress).transferFrom(msg.sender, this, amount)); uint newBal = add(balances[tokenAddress][msg.sender], amount); balances[tokenAddress][msg.sender] = newBal; NewDeposit(tokenAddress, amount); return newBal; } function withdraw( address tokenAddress, uint amount ) public returns (uint) { uint usersBalance = balances[tokenAddress][msg.sender]; amount = min(amount, usersBalance); // R1 require(amount > 0); // R2 require(Token(tokenAddress).transfer(msg.sender, amount)); uint newBal = sub(usersBalance, amount); balances[tokenAddress][msg.sender] = newBal; NewWithdrawal(tokenAddress, amount); return newBal; } function postSellOrder( address sellToken, address buyToken, uint auctionIndex, uint amount ) public returns (uint, uint) { // Note: if a user specifies auctionIndex of 0, it // means he is agnostic which auction his sell order goes into amount = min(amount, balances[sellToken][msg.sender]); // R1 require(amount > 0); // R2 uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken); require(latestAuctionIndex > 0); // R3 uint auctionStart = getAuctionStart(sellToken, buyToken); if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) { // C1: We are in the 10 minute buffer period // OR waiting for an auction to receive sufficient sellVolume // Auction has already cleared, and index has been incremented // sell order must use that auction index // R1.1 if (auctionIndex == 0) { auctionIndex = latestAuctionIndex; } else { require(auctionIndex == latestAuctionIndex); } // R1.2 require(add(sellVolumesCurrent[sellToken][buyToken], amount) < 10 ** 30); } else { // C2 // R2.1: Sell orders must go to next auction if (auctionIndex == 0) { auctionIndex = latestAuctionIndex + 1; } else { require(auctionIndex == latestAuctionIndex + 1); } // R2.2 require(add(sellVolumesNext[sellToken][buyToken], amount) < 10 ** 30); } // Fee mechanism, fees are added to extraTokens uint amountAfterFee = settleFee(sellToken, buyToken, auctionIndex, amount); // Update variables balances[sellToken][msg.sender] = sub(balances[sellToken][msg.sender], amount); uint newSellerBal = add(sellerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee); sellerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newSellerBal; if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) { // C1 uint sellVolumeCurrent = sellVolumesCurrent[sellToken][buyToken]; sellVolumesCurrent[sellToken][buyToken] = add(sellVolumeCurrent, amountAfterFee); } else { // C2 uint sellVolumeNext = sellVolumesNext[sellToken][buyToken]; sellVolumesNext[sellToken][buyToken] = add(sellVolumeNext, amountAfterFee); } if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING) { scheduleNextAuction(sellToken, buyToken); } NewSellOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee); return (auctionIndex, newSellerBal); } function postBuyOrder( address sellToken, address buyToken, uint auctionIndex, uint amount ) public returns (uint) { // R1: auction must not have cleared require(closingPrices[sellToken][buyToken][auctionIndex].den == 0); uint auctionStart = getAuctionStart(sellToken, buyToken); // R2 require(auctionStart <= now); // R4 require(auctionIndex == getAuctionIndex(sellToken, buyToken)); // R5: auction must not be in waiting period require(auctionStart > AUCTION_START_WAITING_FOR_FUNDING); // R6: auction must be funded require(sellVolumesCurrent[sellToken][buyToken] > 0); uint buyVolume = buyVolumes[sellToken][buyToken]; amount = min(amount, balances[buyToken][msg.sender]); // R7 require(add(buyVolume, amount) < 10 ** 30); // Overbuy is when a part of a buy order clears an auction // In that case we only process the part before the overbuy // To calculate overbuy, we first get current price uint sellVolume = sellVolumesCurrent[sellToken][buyToken]; uint num; uint den; (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); // 10^30 * 10^37 = 10^67 uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume)); uint amountAfterFee; if (amount < outstandingVolume) { if (amount > 0) { amountAfterFee = settleFee(buyToken, sellToken, auctionIndex, amount); } } else { amount = outstandingVolume; amountAfterFee = outstandingVolume; } // Here we could also use outstandingVolume or amountAfterFee, it doesn&#39;t matter if (amount > 0) { // Update variables balances[buyToken][msg.sender] = sub(balances[buyToken][msg.sender], amount); uint newBuyerBal = add(buyerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee); buyerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newBuyerBal; buyVolumes[sellToken][buyToken] = add(buyVolumes[sellToken][buyToken], amountAfterFee); NewBuyOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee); } // Checking for equality would suffice here. nevertheless: if (amount >= outstandingVolume) { // Clear auction clearAuction(sellToken, buyToken, auctionIndex, sellVolume); } return (newBuyerBal); } function claimSellerFunds( address sellToken, address buyToken, address user, uint auctionIndex ) public // < (10^60, 10^61) returns (uint returned, uint frtsIssued) { closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex); uint sellerBalance = sellerBalances[sellToken][buyToken][auctionIndex][user]; // R1 require(sellerBalance > 0); // Get closing price for said auction fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex]; uint num = closingPrice.num; uint den = closingPrice.den; // R2: require auction to have cleared require(den > 0); // Calculate return // < 10^30 * 10^30 = 10^60 returned = mul(sellerBalance, num) / den; frtsIssued = issueFrts(sellToken, buyToken, returned, auctionIndex, sellerBalance, user); // Claim tokens sellerBalances[sellToken][buyToken][auctionIndex][user] = 0; if (returned > 0) { balances[buyToken][user] = add(balances[buyToken][user], returned); } NewSellerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued); } function claimBuyerFunds( address sellToken, address buyToken, address user, uint auctionIndex ) public returns (uint returned, uint frtsIssued) { closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex); uint num; uint den; (returned, num, den) = getUnclaimedBuyerFunds(sellToken, buyToken, user, auctionIndex); if (closingPrices[sellToken][buyToken][auctionIndex].den == 0) { // Auction is running claimedAmounts[sellToken][buyToken][auctionIndex][user] = add(claimedAmounts[sellToken][buyToken][auctionIndex][user], returned); } else { // Auction has closed // We DON&#39;T want to check for returned > 0, because that would fail if a user claims // intermediate funds & auction clears in same block (he/she would not be able to claim extraTokens) // Assign extra sell tokens (this is possible only after auction has cleared, // because buyVolume could still increase before that) uint extraTokensTotal = extraTokens[sellToken][buyToken][auctionIndex]; uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user]; // closingPrices.num represents buyVolume // < 10^30 * 10^30 = 10^60 uint tokensExtra = mul(buyerBalance, extraTokensTotal) / closingPrices[sellToken][buyToken][auctionIndex].num; returned = add(returned, tokensExtra); frtsIssued = issueFrts(buyToken, sellToken, mul(buyerBalance, den) / num, auctionIndex, buyerBalance, user); // Auction has closed // Reset buyerBalances and claimedAmounts buyerBalances[sellToken][buyToken][auctionIndex][user] = 0; claimedAmounts[sellToken][buyToken][auctionIndex][user] = 0; } // Claim tokens if (returned > 0) { balances[sellToken][user] = add(balances[sellToken][user], returned); } NewBuyerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued); } function issueFrts( address primaryToken, address secondaryToken, uint x, uint auctionIndex, uint bal, address user ) internal returns (uint frtsIssued) { if (approvedTokens[primaryToken] && approvedTokens[secondaryToken]) { address ethTokenMem = ethToken; // Get frts issued based on ETH price of returned tokens if (primaryToken == ethTokenMem) { frtsIssued = bal; } else if (secondaryToken == ethTokenMem) { // 10^30 * 10^39 = 10^66 frtsIssued = x; } else { // Neither token is ethToken, so we use getHhistoricalPriceOracle() uint pastNum; uint pastDen; (pastNum, pastDen) = getPriceInPastAuction(primaryToken, ethTokenMem, auctionIndex - 1); // 10^30 * 10^35 = 10^65 frtsIssued = mul(bal, pastNum) / pastDen; } if (frtsIssued > 0) { // Issue frtToken frtToken.mintTokens(user, frtsIssued); } } } //@dev allows to close possible theoretical closed markets //@param sellToken sellToken of an auction //@param buyToken buyToken of an auction //@param index is the auctionIndex of the auction function closeTheoreticalClosedAuction( address sellToken, address buyToken, uint auctionIndex ) public { if(auctionIndex == getAuctionIndex(buyToken, sellToken) && closingPrices[sellToken][buyToken][auctionIndex].num == 0) { uint buyVolume = buyVolumes[sellToken][buyToken]; uint sellVolume = sellVolumesCurrent[sellToken][buyToken]; uint num; uint den; (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); // 10^30 * 10^37 = 10^67 uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume)); if(outstandingVolume == 0) { postBuyOrder(sellToken, buyToken, auctionIndex, 0); } } } /// @dev Claim buyer funds for one auction function getUnclaimedBuyerFunds( address sellToken, address buyToken, address user, uint auctionIndex ) public view // < (10^67, 10^37) returns (uint unclaimedBuyerFunds, uint num, uint den) { // R1: checks if particular auction has ever run require(auctionIndex <= getAuctionIndex(sellToken, buyToken)); (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); if (num == 0) { // This should rarely happen - as long as there is >= 1 buy order, // auction will clear before price = 0. So this is just fail-safe unclaimedBuyerFunds = 0; } else { uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user]; // < 10^30 * 10^37 = 10^67 unclaimedBuyerFunds = atleastZero(int( mul(buyerBalance, den) / num - claimedAmounts[sellToken][buyToken][auctionIndex][user] )); } } function settleFee( address primaryToken, address secondaryToken, uint auctionIndex, uint amount ) internal // < 10^30 returns (uint amountAfterFee) { uint feeNum; uint feeDen; (feeNum, feeDen) = getFeeRatio(msg.sender); // 10^30 * 10^3 / 10^4 = 10^29 uint fee = mul(amount, feeNum) / feeDen; if (fee > 0) { fee = settleFeeSecondPart(primaryToken, fee); uint usersExtraTokens = extraTokens[primaryToken][secondaryToken][auctionIndex + 1]; extraTokens[primaryToken][secondaryToken][auctionIndex + 1] = add(usersExtraTokens, fee); Fee(primaryToken, secondaryToken, msg.sender, auctionIndex, fee); } amountAfterFee = sub(amount, fee); } function settleFeeSecondPart( address primaryToken, uint fee ) internal returns (uint newFee) { // Allow user to reduce up to half of the fee with owlToken uint num; uint den; (num, den) = getPriceOfTokenInLastAuction(primaryToken); // Convert fee to ETH, then USD // 10^29 * 10^30 / 10^30 = 10^29 uint feeInETH = mul(fee, num) / den; uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); // 10^29 * 10^6 = 10^35 // Uses 18 decimal places <> exactly as owlToken tokens: 10**18 owlToken == 1 USD uint feeInUSD = mul(feeInETH, ethUSDPrice); uint amountOfowlTokenBurned = min(owlToken.allowance(msg.sender, this), feeInUSD / 2); amountOfowlTokenBurned = min(owlToken.balanceOf(msg.sender), amountOfowlTokenBurned); if (amountOfowlTokenBurned > 0) { owlToken.burnOWL(msg.sender, amountOfowlTokenBurned); // Adjust fee // 10^35 * 10^29 = 10^64 uint adjustment = mul(amountOfowlTokenBurned, fee) / feeInUSD; newFee = sub(fee, adjustment); } else { newFee = fee; } } function getFeeRatio( address user ) public view // feeRatio < 10^4 returns (uint num, uint den) { uint t = frtToken.totalSupply(); uint b = frtToken.lockedTokenBalances(user); if (b * 100000 < t || t == 0) { // 0.5% num = 1; den = 200; } else if (b * 10000 < t) { // 0.4% num = 1; den = 250; } else if (b * 1000 < t) { // 0.3% num = 3; den = 1000; } else if (b * 100 < t) { // 0.2% num = 1; den = 500; } else if (b * 10 < t) { // 0.1% num = 1; den = 1000; } else { // 0% num = 0; den = 1; } } /// @dev clears an Auction /// @param sellToken sellToken of the auction /// @param buyToken buyToken of the auction /// @param auctionIndex of the auction to be cleared. function clearAuction( address sellToken, address buyToken, uint auctionIndex, uint sellVolume ) internal { // Get variables uint buyVolume = buyVolumes[sellToken][buyToken]; uint sellVolumeOpp = sellVolumesCurrent[buyToken][sellToken]; uint closingPriceOppDen = closingPrices[buyToken][sellToken][auctionIndex].den; uint auctionStart = getAuctionStart(sellToken, buyToken); // Update closing price if (sellVolume > 0) { closingPrices[sellToken][buyToken][auctionIndex] = fraction(buyVolume, sellVolume); } // if (opposite is 0 auction OR price = 0 OR opposite auction cleared) // price = 0 happens if auction pair has been running for >= 24 hrs = 86400 if (sellVolumeOpp == 0 || now >= auctionStart + 86400 || closingPriceOppDen > 0) { // Close auction pair uint buyVolumeOpp = buyVolumes[buyToken][sellToken]; if (closingPriceOppDen == 0 && sellVolumeOpp > 0) { // Save opposite price closingPrices[buyToken][sellToken][auctionIndex] = fraction(buyVolumeOpp, sellVolumeOpp); } uint sellVolumeNext = sellVolumesNext[sellToken][buyToken]; uint sellVolumeNextOpp = sellVolumesNext[buyToken][sellToken]; // Update state variables for both auctions sellVolumesCurrent[sellToken][buyToken] = sellVolumeNext; if (sellVolumeNext > 0) { sellVolumesNext[sellToken][buyToken] = 0; } if (buyVolume > 0) { buyVolumes[sellToken][buyToken] = 0; } sellVolumesCurrent[buyToken][sellToken] = sellVolumeNextOpp; if (sellVolumeNextOpp > 0) { sellVolumesNext[buyToken][sellToken] = 0; } if (buyVolumeOpp > 0) { buyVolumes[buyToken][sellToken] = 0; } // Increment auction index setAuctionIndex(sellToken, buyToken); // Check if next auction can be scheduled scheduleNextAuction(sellToken, buyToken); } AuctionCleared(sellToken, buyToken, sellVolume, buyVolume, auctionIndex); } function scheduleNextAuction( address sellToken, address buyToken ) internal { // Check if auctions received enough sell orders uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); uint sellNum; uint sellDen; (sellNum, sellDen) = getPriceOfTokenInLastAuction(sellToken); uint buyNum; uint buyDen; (buyNum, buyDen) = getPriceOfTokenInLastAuction(buyToken); // We use current sell volume, because in clearAuction() we set // sellVolumesCurrent = sellVolumesNext before calling this function // (this is so that we don&#39;t need case work, // since it might also be called from postSellOrder()) // < 10^30 * 10^31 * 10^6 = 10^67 uint sellVolume = mul(mul(sellVolumesCurrent[sellToken][buyToken], sellNum), ethUSDPrice) / sellDen; uint sellVolumeOpp = mul(mul(sellVolumesCurrent[buyToken][sellToken], buyNum), ethUSDPrice) / buyDen; if (sellVolume >= thresholdNewAuction || sellVolumeOpp >= thresholdNewAuction) { // Schedule next auction setAuctionStart(sellToken, buyToken, WAITING_PERIOD_NEW_AUCTION); } else { resetAuctionStart(sellToken, buyToken); } } //@ dev returns price in units [token2]/[token1] //@ param token1 first token for price calculation //@ param token2 second token for price calculation //@ param auctionIndex index for the auction to get the averaged price from function getPriceInPastAuction( address token1, address token2, uint auctionIndex ) public view // price < 10^31 returns (uint num, uint den) { if (token1 == token2) { // C1 num = 1; den = 1; } else { // C2 // R2.1 require(auctionIndex >= 0); // C3 // R3.1 require(auctionIndex <= getAuctionIndex(token1, token2)); // auction still running uint i = 0; bool correctPair = false; fraction memory closingPriceToken1; fraction memory closingPriceToken2; while (!correctPair) { closingPriceToken2 = closingPrices[token2][token1][auctionIndex - i]; closingPriceToken1 = closingPrices[token1][token2][auctionIndex - i]; if (closingPriceToken1.num > 0 && closingPriceToken1.den > 0 || closingPriceToken2.num > 0 && closingPriceToken2.den > 0) { correctPair = true; } i++; } // At this point at least one closing price is strictly positive // If only one is positive, we want to output that if (closingPriceToken1.num == 0 || closingPriceToken1.den == 0) { num = closingPriceToken2.den; den = closingPriceToken2.num; } else if (closingPriceToken2.num == 0 || closingPriceToken2.den == 0) { num = closingPriceToken1.num; den = closingPriceToken1.den; } else { // If both prices are positive, output weighted average num = closingPriceToken2.den + closingPriceToken1.num; den = closingPriceToken2.num + closingPriceToken1.den; } } } /// @dev Gives best estimate for market price of a token in ETH of any price oracle on the Ethereum network /// @param token address of ERC-20 token /// @return Weighted average of closing prices of opposite Token-ethToken auctions, based on their sellVolume function getPriceOfTokenInLastAuction( address token ) public view // price < 10^31 returns (uint num, uint den) { uint latestAuctionIndex = getAuctionIndex(token, ethToken); // getPriceInPastAuction < 10^30 (num, den) = getPriceInPastAuction(token, ethToken, latestAuctionIndex - 1); } function getCurrentAuctionPrice( address sellToken, address buyToken, uint auctionIndex ) public view // price < 10^37 returns (uint num, uint den) { fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex]; if (closingPrice.den != 0) { // Auction has closed (num, den) = (closingPrice.num, closingPrice.den); } else if (auctionIndex > getAuctionIndex(sellToken, buyToken)) { (num, den) = (0, 0); } else { // Auction is running uint pastNum; uint pastDen; (pastNum, pastDen) = getPriceInPastAuction(sellToken, buyToken, auctionIndex - 1); // If we&#39;re calling the function into an unstarted auction, // it will return the starting price of that auction uint timeElapsed = atleastZero(int(now - getAuctionStart(sellToken, buyToken))); // The numbers below are chosen such that // P(0 hrs) = 2 * lastClosingPrice, P(6 hrs) = lastClosingPrice, P(>=24 hrs) = 0 // 10^5 * 10^31 = 10^36 num = atleastZero(int((86400 - timeElapsed) * pastNum)); // 10^6 * 10^31 = 10^37 den = mul((timeElapsed + 43200), pastDen); if (mul(num, sellVolumesCurrent[sellToken][buyToken]) <= mul(den, buyVolumes[sellToken][buyToken])) { num = buyVolumes[sellToken][buyToken]; den = sellVolumesCurrent[sellToken][buyToken]; } } } function depositAndSell( address sellToken, address buyToken, uint amount ) external returns (uint newBal, uint auctionIndex, uint newSellerBal) { newBal = deposit(sellToken, amount); (auctionIndex, newSellerBal) = postSellOrder(sellToken, buyToken, 0, amount); } function claimAndWithdraw( address sellToken, address buyToken, address user, uint auctionIndex, uint amount ) external returns (uint returned, uint frtsIssued, uint newBal) { (returned, frtsIssued) = claimSellerFunds(sellToken, buyToken, user, auctionIndex); newBal = withdraw(buyToken, amount); } // > Helper fns function getTokenOrder( address token1, address token2 ) public pure returns (address, address) { if (token2 < token1) { (token1, token2) = (token2, token1); } return (token1, token2); } function setAuctionStart( address token1, address token2, uint value ) internal { (token1, token2) = getTokenOrder(token1, token2); uint auctionStart = now + value; uint auctionIndex = latestAuctionIndices[token1][token2]; auctionStarts[token1][token2] = auctionStart; AuctionStartScheduled(token1, token2, auctionIndex, auctionStart); } function resetAuctionStart( address token1, address token2 ) internal { (token1, token2) = getTokenOrder(token1, token2); if (auctionStarts[token1][token2] != AUCTION_START_WAITING_FOR_FUNDING) { auctionStarts[token1][token2] = AUCTION_START_WAITING_FOR_FUNDING; } } function getAuctionStart( address token1, address token2 ) public view returns (uint auctionStart) { (token1, token2) = getTokenOrder(token1, token2); auctionStart = auctionStarts[token1][token2]; } function setAuctionIndex( address token1, address token2 ) internal { (token1, token2) = getTokenOrder(token1, token2); latestAuctionIndices[token1][token2] += 1; } function getAuctionIndex( address token1, address token2 ) public view returns (uint auctionIndex) { (token1, token2) = getTokenOrder(token1, token2); auctionIndex = latestAuctionIndices[token1][token2]; } // > Math fns function min(uint a, uint b) public pure returns (uint) { if (a < b) { return a; } else { return b; } } function atleastZero(int a) public pure returns (uint) { if (a < 0) { return 0; } else { return uint(a); } } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) public pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) public pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) public pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) public pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) public pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) public pure returns (uint) { require(safeToMul(a, b)); return a * b; } function getRunningTokenPairs( address[] tokens ) external view returns (address[] tokens1, address[] tokens2) { uint arrayLength; for (uint k = 0; k < tokens.length - 1; k++) { for (uint l = k + 1; l < tokens.length; l++) { if (getAuctionIndex(tokens[k], tokens[l]) > 0) { arrayLength++; } } } tokens1 = new address[](arrayLength); tokens2 = new address[](arrayLength); uint h; for (uint i = 0; i < tokens.length - 1; i++) { for (uint j = i + 1; j < tokens.length; j++) { if (getAuctionIndex(tokens[i], tokens[j]) > 0) { tokens1[h] = tokens[i]; tokens2[h] = tokens[j]; h++; } } } } //@dev for quick overview of possible sellerBalances to calculate the possible withdraw tokens //@param auctionSellToken is the sellToken defining an auctionPair //@param auctionBuyToken is the buyToken defining an auctionPair //@param user is the user who wants to his tokens //@param lastNAuctions how many auctions will be checked. 0 means all //@returns returns sellbal for all indices for all tokenpairs function getIndicesWithClaimableTokensForSellers( address auctionSellToken, address auctionBuyToken, address user, uint lastNAuctions ) external view returns(uint[] indices, uint[] usersBalances) { uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken); uint arrayLength; uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1; for (uint j = startingIndex; j <= runningAuctionIndex; j++) { if (sellerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) { arrayLength++; } } indices = new uint[](arrayLength); usersBalances = new uint[](arrayLength); uint k; for (uint i = startingIndex; i <= runningAuctionIndex; i++) { if (sellerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) { indices[k] = i; usersBalances[k] = sellerBalances[auctionSellToken][auctionBuyToken][i][user]; k++; } } } //@dev for quick overview of current sellerBalances for a user //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param user is the user who wants to his tokens function getSellerBalancesOfCurrentAuctions( address[] auctionSellTokens, address[] auctionBuyTokens, address user ) external view returns (uint[]) { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint[] memory sellersBalances = new uint[](length); for (uint i = 0; i < length; i++) { uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]); sellersBalances[i] = sellerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user]; } return sellersBalances; } //@dev for quick overview of possible buyerBalances to calculate the possible withdraw tokens //@param auctionSellToken is the sellToken defining an auctionPair //@param auctionBuyToken is the buyToken defining an auctionPair //@param user is the user who wants to his tokens //@param lastNAuctions how many auctions will be checked. 0 means all //@returns returns sellbal for all indices for all tokenpairs function getIndicesWithClaimableTokensForBuyers( address auctionSellToken, address auctionBuyToken, address user, uint lastNAuctions ) external view returns(uint[] indices, uint[] usersBalances) { uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken); uint arrayLength; uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1; for (uint j = startingIndex; j <= runningAuctionIndex; j++) { if (buyerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) { arrayLength++; } } indices = new uint[](arrayLength); usersBalances = new uint[](arrayLength); uint k; for (uint i = startingIndex; i <= runningAuctionIndex; i++) { if (buyerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) { indices[k] = i; usersBalances[k] = buyerBalances[auctionSellToken][auctionBuyToken][i][user]; k++; } } } //@dev for quick overview of current sellerBalances for a user //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param user is the user who wants to his tokens function getBuyerBalancesOfCurrentAuctions( address[] auctionSellTokens, address[] auctionBuyTokens, address user ) external view returns (uint[]) { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint[] memory buyersBalances = new uint[](length); for (uint i = 0; i < length; i++) { uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]); buyersBalances[i] = buyerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user]; } return buyersBalances; } //@dev for quick overview of approved Tokens //@param addressesToCheck are the ERC-20 token addresses to be checked whether they are approved function getApprovedAddressesOfList( address[] addressToCheck ) external view returns (bool[]) { uint length = addressToCheck.length; bool[] memory isApproved = new bool[](length); for (uint i = 0; i < length; i++) { isApproved[i] = approvedTokens[addressToCheck[i]]; } return isApproved; } //@dev for multiple withdraws //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param auctionIndices are the auction indices on which an token should be claimedAmounts //@param user is the user who wants to his tokens function claimTokensFromSeveralAuctionsAsSeller( address[] auctionSellTokens, address[] auctionBuyTokens, uint[] auctionIndices, address user ) external { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint length3 = auctionIndices.length; require(length2 == length3); for (uint i = 0; i < length; i++) claimSellerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]); } //@dev for multiple withdraws //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param auctionIndices are the auction indices on which an token should be claimedAmounts //@param user is the user who wants to his tokens function claimTokensFromSeveralAuctionsAsBuyer( address[] auctionSellTokens, address[] auctionBuyTokens, uint[] auctionIndices, address user ) external { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint length3 = auctionIndices.length; require(length2 == length3); for (uint i = 0; i < length; i++) claimBuyerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]); } function getMasterCopy() external view returns (address) { return masterCopy; } // > Events event NewDeposit( address indexed token, uint amount ); event NewOracleProposal( PriceOracleInterface priceOracleInterface ); event NewMasterCopyProposal( address newMasterCopy ); event NewWithdrawal( address indexed token, uint amount ); event NewSellOrder( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount ); event NewBuyOrder( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount ); event NewSellerFundsClaim( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount, uint frtsIssued ); event NewBuyerFundsClaim( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount, uint frtsIssued ); event NewTokenPair( address indexed sellToken, address indexed buyToken ); event AuctionCleared( address indexed sellToken, address indexed buyToken, uint sellVolume, uint buyVolume, uint indexed auctionIndex ); event Approval( address indexed token, bool approved ); event AuctionStartScheduled( address indexed sellToken, address indexed buyToken, uint indexed auctionIndex, uint auctionStart ); event Fee( address indexed primaryToken, address indexed secondarToken, address indexed user, uint auctionIndex, uint fee ); }
for quick overview of approved Tokens addressesToCheck are the ERC-20 token addresses to be checked whether they are approved
function getApprovedAddressesOfList( address[] addressToCheck ) external view returns (bool[]) { uint length = addressToCheck.length; bool[] memory isApproved = new bool[](length); for (uint i = 0; i < length; i++) { isApproved[i] = approvedTokens[addressToCheck[i]]; } return isApproved; }
7,683,299
./partial_match/3/0xAAa655f350eF27981dcDfC2B82d3DA52D8D1cf45/sources/Governance.sol
approve or deny for the proposal by deposit./
function vote( bytes32 proposeId, bool approval, uint128 amount ) external override { bytes32 account = keccak256(abi.encode(proposeId, msg.sender)); require( (_proposeStatus[proposeId].lockin && _proposeStatus[proposeId].mainvoteDeadline >= _getBlockTimestampSec()) || _proposeStatus[proposeId].prevoteDeadline >= _getBlockTimestampSec(), "voting period has expired" ); if (approval) { _proposeStatus[proposeId].currentApprovalVoteSum = _proposeStatus[proposeId] .currentApprovalVoteSum .add(amount) .toUint128(); _amountOfVotes[account].approval = _amountOfVotes[account].approval.add(amount).toUint128(); _proposeStatus[proposeId].currentDenialVoteSum = _proposeStatus[proposeId] .currentDenialVoteSum .add(amount) .toUint128(); _amountOfVotes[account].denial = _amountOfVotes[account].denial.add(amount).toUint128(); } _lockStakingToken(msg.sender, amount); emit LogDeposit(proposeId, msg.sender, approval, amount); }
5,230,194
pragma solidity ^0.4.18; /** * @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; } } /** * @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 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(); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract 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]; } } 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; } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract MintableToken is PausableToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract TokenImpl is MintableToken { string public name; string public symbol; // how many token units a buyer gets per ether uint256 public rate; uint256 public eth_decimal_num = 100000; // the target token ERC20Basic public targetToken; uint256 public exchangedNum; event Exchanged(address _owner, uint256 _value); function TokenImpl(string _name, string _symbol, uint256 _decimal_num) public { name = _name; symbol = _symbol; eth_decimal_num = _decimal_num; paused = true; } /** * @dev exchange tokens of _exchanger. */ function exchange(address _exchanger, uint256 _value) internal { require(canExchange()); uint256 _tokens = (_value.mul(rate)).div(eth_decimal_num); targetToken.transfer(_exchanger, _tokens); exchangedNum = exchangedNum.add(_value); Exchanged(_exchanger, _tokens); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (_to == address(this) || _to == owner) { exchange(msg.sender, _value); } return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool) { if (_to == address(this) || _to == owner) { exchange(msg.sender, _value); } return super.transfer(_to, _value); } function balanceOfTarget(address _owner) public view returns (uint256 targetBalance) { if (targetToken != address(0)) { return targetToken.balanceOf(_owner); } else { return 0; } } function canExchangeNum() public view returns (uint256) { if (canExchange()) { uint256 _tokens = targetToken.balanceOf(this); return (eth_decimal_num.mul(_tokens)).div(rate); } else { return 0; } } function updateTargetToken(address _target, uint256 _rate) onlyOwner public { rate = _rate; targetToken = ERC20Basic(_target); } function canExchange() public view returns (bool) { return targetToken != address(0) && rate > 0; } } contract Crowdsale is Pausable { using SafeMath for uint256; string public projectName; string public tokenName; string public tokenSymbol; // how many token units a buyer gets per ether uint256 public rate; // amount of raised money in wei, decimals is 5 uint256 public ethRaised; uint256 public eth_decimal_num = 100000; // cap of money in wei uint256 public cap; // The token being sold TokenImpl public token; // the target token ERC20Basic public targetToken; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value); event IncreaseCap(uint256 cap); event DecreaseCap(uint256 cap); function Crowdsale(string _projectName, string _tokenName, string _tokenSymbol, uint256 _cap) public { require(_cap > 0); projectName = _projectName; tokenName = _tokenName; tokenSymbol = _tokenSymbol; cap = _cap.mul(eth_decimal_num); token = createTokenContract(); } function newCrowdSale(string _projectName, string _tokenName, string _tokenSymbol, uint256 _cap) onlyOwner public { require(_cap > 0); projectName = _projectName; tokenName = _tokenName; tokenSymbol = _tokenSymbol; cap = _cap.mul(eth_decimal_num); ethRaised = 0; token.transferOwnership(owner); token = createTokenContract(); rate = 0; targetToken = ERC20Basic(0); } function createTokenContract() internal returns (TokenImpl) { return new TokenImpl(tokenName, tokenSymbol, eth_decimal_num); } // fallback function can be used to buy tokens function() external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != address(0)); require(msg.value >= (0.00001 ether)); uint256 ethAmount = (msg.value.mul(eth_decimal_num)).div(1 ether); // update state ethRaised = ethRaised.add(ethAmount); require(ethRaised <= cap); token.mint(beneficiary, ethAmount); TokenPurchase(msg.sender, beneficiary, ethAmount); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { owner.transfer(msg.value); } // increase the amount of eth function increaseCap(uint256 _cap_inc) onlyOwner public { require(_cap_inc > 0); cap = cap.add(_cap_inc.mul(eth_decimal_num)); IncreaseCap(cap); } function decreaseCap(uint256 _cap_dec) onlyOwner public { require(_cap_dec > 0); cap = cap.sub(_cap_dec.mul(eth_decimal_num)); if (cap <= ethRaised) { cap = ethRaised; } DecreaseCap(cap); } function saleRatio() public view returns (uint256 ratio) { if (cap == 0) { return 0; } else { return ethRaised.mul(10000).div(cap); } } function balanceOf(address _owner) public view returns (uint256 balance) { return token.balanceOf(_owner); } function balanceOfTarget(address _owner) public view returns (uint256 targetBalance) { return token.balanceOfTarget(_owner); } function canExchangeNum() public view returns (uint256) { return token.canExchangeNum(); } function updateTargetToken(address _target, uint256 _rate) onlyOwner public { rate = _rate; targetToken = ERC20Basic(_target); token.updateTargetToken(_target, _rate); } /** * @dev called by the owner to transfer the target token to owner from this contact */ function releaseTargetToken(uint256 _value) onlyOwner public returns (bool) { if (targetToken != address(0)) { return targetToken.transfer(owner, _value); } else { return false; } } /** * @dev called by the owner to pause, triggers stopped state */ function pauseToken() onlyOwner public { token.pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpauseToken() onlyOwner public { token.unpause(); } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return ethRaised >= cap; } }
called by the owner to unpause, returns to normal state/
function unpauseToken() onlyOwner public { token.unpause(); }
13,132,031
./full_match/11155111/0x9b024EB9087f307C7dc19dFB0eC7e9D8F51D2E71/sources/contracts/HoneyCastContract.sol
Prevent reentrancy attacks
function withdrawMintFunds() public payable onlyOwner { uint256 ownerPayout = pendingBalances[OPA]; uint256 kingdomlyFee = pendingBalances[KPA]; pendingBalances[OPA] = 0; pendingBalances[KPA] = 0; require(success1 && success2, "Withdraw Transfer Failed"); }
3,829,615
pragma solidity 0.4.25; // File: contracts/saga/interfaces/IMonetaryModel.sol /** * @title Monetary Model Interface. */ interface IMonetaryModel { /** * @dev Buy SGA in exchange for SDR. * @param _sdrAmount The amount of SDR received from the buyer. * @return The amount of SGA that the buyer is entitled to receive. */ function buy(uint256 _sdrAmount) external returns (uint256); /** * @dev Sell SGA in exchange for SDR. * @param _sgaAmount The amount of SGA received from the seller. * @return The amount of SDR that the seller is entitled to receive. */ function sell(uint256 _sgaAmount) external returns (uint256); } // File: contracts/saga/interfaces/IReconciliationAdjuster.sol /** * @title Reconciliation Adjuster Interface. */ interface IReconciliationAdjuster { /** * @dev Get the buy-adjusted value of a given SDR amount. * @param _sdrAmount The amount of SDR to adjust. * @return The adjusted amount of SDR. */ function adjustBuy(uint256 _sdrAmount) external view returns (uint256); /** * @dev Get the sell-adjusted value of a given SDR amount. * @param _sdrAmount The amount of SDR to adjust. * @return The adjusted amount of SDR. */ function adjustSell(uint256 _sdrAmount) external view returns (uint256); } // File: contracts/saga/interfaces/ITransactionManager.sol /** * @title Transaction Manager Interface. */ interface ITransactionManager { /** * @dev Buy SGA in exchange for ETH. * @param _ethAmount The amount of ETH received from the buyer. * @return The amount of SGA that the buyer is entitled to receive. */ function buy(uint256 _ethAmount) external returns (uint256); /** * @dev Sell SGA in exchange for ETH. * @param _sgaAmount The amount of SGA received from the seller. * @return The amount of ETH that the seller is entitled to receive. */ function sell(uint256 _sgaAmount) external returns (uint256); } // File: contracts/saga/interfaces/ITransactionLimiter.sol /** * @title Transaction Limiter Interface. */ interface ITransactionLimiter { /** * @dev Reset the total buy-amount and the total sell-amount. */ function resetTotal() external; /** * @dev Increment the total buy-amount. * @param _amount The amount to increment by. */ function incTotalBuy(uint256 _amount) external; /** * @dev Increment the total sell-amount. * @param _amount The amount to increment by. */ function incTotalSell(uint256 _amount) external; } // File: contracts/saga/interfaces/IETHConverter.sol /** * @title ETH Converter Interface. */ interface IETHConverter { /** * @dev Get the current SDR worth of a given ETH amount. * @param _ethAmount The amount of ETH to convert. * @return The equivalent amount of SDR. */ function toSdrAmount(uint256 _ethAmount) external view returns (uint256); /** * @dev Get the current ETH worth of a given SDR amount. * @param _sdrAmount The amount of SDR to convert. * @return The equivalent amount of ETH. */ function toEthAmount(uint256 _sdrAmount) external view returns (uint256); /** * @dev Get the original SDR worth of a converted ETH amount. * @param _ethAmount The amount of ETH converted. * @return The original amount of SDR. */ function fromEthAmount(uint256 _ethAmount) external view returns (uint256); } // File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol /** * @title Contract Address Locator Interface. */ interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } // File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol /** * @title Contract Address Locator Holder. * @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system. * @dev Any contract which inherits from this contract can retrieve the address of any contract in the system. * @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system. * @dev In addition to that, any function in any contract can be restricted to a specific caller. */ contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGAAuthorizationManager_ = "ISGAAuthorizationManager"; bytes32 internal constant _ISGAToken_ = "ISGAToken" ; bytes32 internal constant _ISGATokenManager_ = "ISGATokenManager" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _IWalletsTradingDataSource_ = "IWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _WalletsTradingLimiter_SGATokenManager_ = "WalletsTLSGATokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; IContractAddressLocator private contractAddressLocator; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } /** * @dev Get the contract address locator. * @return The contract address locator. */ function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } /** * @dev Determine whether or not the sender relates to one of the identifiers. * @param _identifiers The identifiers. * @return A boolean indicating if the sender relates to one of the identifiers. */ function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } /** * @dev Verify that the caller is mapped to a given identifier. * @param _identifier The identifier. */ modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } // File: contracts/saga/TransactionManager.sol /** * Details of usage of licenced software see here: https://www.saga.org/software/readme_v1 */ /** * @title Transaction Manager. */ contract TransactionManager is ITransactionManager, ContractAddressLocatorHolder { string public constant VERSION = "1.0.0"; event TransactionManagerBuyCompleted(uint256 _amount); event TransactionManagerSellCompleted(uint256 _amount); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the IMonetaryModel interface. */ function getMonetaryModel() public view returns (IMonetaryModel) { return IMonetaryModel(getContractAddress(_IMonetaryModel_)); } /** * @dev Return the contract which implements the IReconciliationAdjuster interface. */ function getReconciliationAdjuster() public view returns (IReconciliationAdjuster) { return IReconciliationAdjuster(getContractAddress(_IReconciliationAdjuster_)); } /** * @dev Return the contract which implements the ITransactionLimiter interface. */ function getTransactionLimiter() public view returns (ITransactionLimiter) { return ITransactionLimiter(getContractAddress(_ITransactionLimiter_)); } /** * @dev Return the contract which implements the IETHConverter interface. */ function getETHConverter() public view returns (IETHConverter) { return IETHConverter(getContractAddress(_IETHConverter_)); } /** * @dev Buy SGA in exchange for ETH. * @param _ethAmount The amount of ETH received from the buyer. * @return The amount of SGA that the buyer is entitled to receive. */ function buy(uint256 _ethAmount) external only(_ISGATokenManager_) returns (uint256) { uint256 sdrAmount = getETHConverter().toSdrAmount(_ethAmount); uint256 newAmount = getReconciliationAdjuster().adjustBuy(sdrAmount); uint256 sgaAmount = getMonetaryModel().buy(newAmount); getTransactionLimiter().incTotalBuy(sdrAmount); emit TransactionManagerBuyCompleted(sdrAmount); return sgaAmount; } /** * @dev Sell SGA in exchange for ETH. * @param _sgaAmount The amount of SGA received from the seller. * @return The amount of ETH that the seller is entitled to receive. */ function sell(uint256 _sgaAmount) external only(_ISGATokenManager_) returns (uint256) { uint256 sdrAmount = getMonetaryModel().sell(_sgaAmount); uint256 newAmount = getReconciliationAdjuster().adjustSell(sdrAmount); uint256 ethAmount = getETHConverter().toEthAmount(newAmount); getTransactionLimiter().incTotalSell(sdrAmount); emit TransactionManagerSellCompleted(newAmount); return ethAmount; } }
Sell SGA in exchange for ETH. _sgaAmount The amount of SGA received from the seller. return The amount of ETH that the seller is entitled to receive./
function sell(uint256 _sgaAmount) external only(_ISGATokenManager_) returns (uint256) { uint256 sdrAmount = getMonetaryModel().sell(_sgaAmount); uint256 newAmount = getReconciliationAdjuster().adjustSell(sdrAmount); uint256 ethAmount = getETHConverter().toEthAmount(newAmount); getTransactionLimiter().incTotalSell(sdrAmount); emit TransactionManagerSellCompleted(newAmount); return ethAmount; }
7,311,003
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev Interface for Belt staking contract. */ interface IMasterBelt { function deposit(uint256 _pid, uint256 _wantAmt) external; function withdraw(uint256 _pid, uint256 _wantAmt) external; function stakedWantTokens(uint256 _pid, address _user) external view returns (uint256); function pendingBELT(uint256 _pid, address _user) external view returns (uint256); }
Interface for Belt staking contract./
interface IMasterBelt { function deposit(uint256 _pid, uint256 _wantAmt) external; function withdraw(uint256 _pid, uint256 _wantAmt) external; function stakedWantTokens(uint256 _pid, address _user) external view returns (uint256); function pendingBELT(uint256 _pid, address _user) external view returns (uint256); pragma solidity 0.8.0; }
12,660,126
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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: LGPL-3.0-or-later pragma solidity 0.7.4; import "@openzeppelin/contracts/access/AccessControl.sol"; contract KRoles is AccessControl { bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); event OperatorAdded(address indexed account); event OperatorRemoved(address indexed account); constructor(address _operator) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _operator); } modifier onlyOperator() { require(isOperator(_msgSender()), "OperatorRole: caller does not have the Operator role"); _; } function isOperator(address account) public view returns (bool) { return hasRole(OPERATOR_ROLE, account); } function addOperator(address account) public onlyOperator { _addOperator(account); } function renounceOperator() public virtual { _renounceOperator(msg.sender); } function _addOperator(address account) internal { grantRole(OPERATOR_ROLE, account); emit OperatorAdded(account); } function _renounceOperator(address account) internal { renounceRole(OPERATOR_ROLE, account); emit OperatorRemoved(account); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.4; import "./StandardToken.sol"; contract KToken is StandardToken { address private underlying_; constructor(string memory name, string memory symbol, uint8 decimals, address _underlying) StandardToken(name, symbol, decimals) { underlying_ = _underlying; } /// @return The address of the underlying token. function underlying() public view returns (address) { return underlying_; } } contract kEther is KToken { constructor() KToken("kEther", "kETH", 18, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {} } contract kWrappedEther is KToken { constructor(address _underlying) KToken("kWrappedEther", "kwETH", 18, _underlying) {} } contract kUSDC is KToken { constructor(address _underlying) KToken("kUSDCoin", "kUSDC", 6, _underlying) {} } contract kWBTC is KToken { constructor(address _underlying) KToken("kWrappedBitcoin", "kWBTC", 8, _underlying) {} } contract kBTC is KToken { constructor(address _underlying) KToken("kBitcoin", "kBTC", 8, _underlying) {} } contract kDAI is KToken { constructor(address _underlying) KToken("kDAI", "kDAI", 18, _underlying) {} } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.4; import "./common/CanReclaimTokens.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; contract StandardToken is ERC20, AccessControl, ERC20Burnable, CanReclaimTokens { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); constructor(string memory name, string memory symbol, uint8 decimals) ERC20(name, symbol) CanReclaimTokens(_msgSender()) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupDecimals(decimals); } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "MinterRole: caller does not have the Minter role"); _; } function addMinter(address _newMinter) onlyMinter external { grantRole(MINTER_ROLE, _newMinter); grantRole(DEFAULT_ADMIN_ROLE, _newMinter); } function renounceMinter() onlyMinter external { renounceRole(MINTER_ROLE, _msgSender()); renounceRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function mint(address account, uint256 amount) onlyMinter public returns (bool) { _mint(account, amount); return true; } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity 0.7.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "../KRoles.sol"; contract CanReclaimTokens is KRoles { using SafeERC20 for ERC20; mapping(address => bool) private recoverableTokensBlacklist; constructor(address _nextOwner) KRoles(_nextOwner) {} function blacklistRecoverableToken(address _token) public onlyOperator { recoverableTokensBlacklist[_token] = true; } /// @notice Allow the owner of the contract to recover funds accidentally /// sent to the contract. To withdraw ETH, the token should be set to `0x0`. function recoverTokens(address _token) external onlyOperator { require( !recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable" ); if (_token == address(0x0)) { (bool success,) = msg.sender.call{ value: address(this).balance }(""); require(success, "Transfer Failed"); } else { ERC20(_token).safeTransfer( msg.sender, ERC20(_token).balanceOf(address(this)) ); } } }
Allow the owner of the contract to recover funds accidentally sent to the contract. To withdraw ETH, the token should be set to `0x0`.
function recoverTokens(address _token) external onlyOperator { require( !recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable" ); if (_token == address(0x0)) { require(success, "Transfer Failed"); ERC20(_token).safeTransfer( msg.sender, ERC20(_token).balanceOf(address(this)) ); } }
6,905,490
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies 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.3._ */ 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.3._ */ 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.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.0; contract YeaHammer is ERC721Pausable, Ownable { uint256 private _maxTotalSupply; mapping(address => bool) public _minters; constructor() public ERC721("yea.hammer", "yeah") { _maxTotalSupply = 66600; setBaseURI("https://www.douyea.com/hammer-resources/hammer/"); addMinter(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyMinter() { require(_minters[msg.sender], "Minter: caller is not the owner"); _; } function mint(address player, uint256 id) public onlyMinter returns (uint256) { require(id <= _maxTotalSupply && id > 0, "Minter: mine pool is empty"); _mint(player, id); _setTokenURI(id, Strings.toString(id)); return id; } function setBaseURI(string memory baseURI) public onlyOwner virtual { _setBaseURI(baseURI); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public virtual onlyOwner whenNotPaused { _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public virtual onlyOwner whenPaused { _unpause(); } function addMinter(address minter) public onlyOwner { _minters[minter] = true; } function removeMinter(address minter) public onlyOwner { _minters[minter] = false; } function burn(uint256 tokenId) public onlyOwner { _burn(tokenId); } }
Returns to normal state. Requirements: - The contract must be paused./
function unpause() public virtual onlyOwner whenPaused { _unpause(); }
6,336,813
pragma solidity 0.4.23; contract ERC20BasicInterface { function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } /** * @title ERC20Lock * * This contract keeps particular token till the unlock date and sends it to predefined destination. */ contract DLSDLockAdvisors3 { ERC20BasicInterface constant TOKEN = ERC20BasicInterface(0x8458d484572cEB89ce70EEBBe17Dc84707b241eD); address constant OWNER = 0x603F65F7Fc4f650c2F025800F882CFb62BF23580; address constant DESTINATION = 0x309F0716701f346F2aE84ec9a45ce7E69E747f18; uint constant UNLOCK_DATE = 1548547199; // Saturday, January 26, 2019 11:59:59 PM function unlock() public returns(bool) { require(now > UNLOCK_DATE, 'Tokens are still locked'); return TOKEN.transfer(DESTINATION, TOKEN.balanceOf(address(this))); } function recoverTokens(ERC20BasicInterface _token, address _to, uint _value) public returns(bool) { require(msg.sender == OWNER, 'Access denied'); // This token meant to be recovered by calling unlock(). require(address(_token) != address(TOKEN), 'Can not recover this token'); return _token.transfer(_to, _value); } }
This token meant to be recovered by calling unlock().
function recoverTokens(ERC20BasicInterface _token, address _to, uint _value) public returns(bool) { require(msg.sender == OWNER, 'Access denied'); require(address(_token) != address(TOKEN), 'Can not recover this token'); return _token.transfer(_to, _value); }
5,382,509
./full_match/4/0x2eCBe30EdccDeF3e4D0535658Ac0cc0E9a8c0aFD/sources/contracts/LP.sol
Core: Change amount of reserved by conditions funds. initReserve reinforcement of the condition. finalReserve amount of reserves that was not demand according to the condition results, when condition is canceling passed value is 0/ pool win calc oracle rewards calc DAO rewards add profit to segmentTree send oracle profit remove loss from segmentTree excluding canceled conditions (when finalReserve = initReserve)
function addReserve( uint128 initReserve, uint128 finalReserve, uint48 leaf, address oracle ) external override onlyCore { if (finalReserve > initReserve) { uint128 profit = finalReserve - initReserve; uint128 oracleRewards = (profit * oracleFee) / multiplier; uint128 daoRewards = (profit * daoFee) / multiplier; totalDaoRewards += daoRewards; addLimit(profit - (oracleRewards + daoRewards), leaf); TransferHelper.safeTransfer(token, oracle, oracleRewards); if (initReserve - finalReserve > 0) { remove(initReserve - finalReserve); } } }
752,254
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import {IERC20} from '../ERC20/IERC20.sol'; import {SafeMath} from '../utils/math/SafeMath.sol'; import {IARTHPool} from './Pools/IARTHPool.sol'; import {IARTHController} from './IARTHController.sol'; import {AccessControl} from '../access/AccessControl.sol'; import { IUniswapPairOracle } from '../Oracle/Variants/uniswap/IUniswapPairOracle.sol'; import {IOracle} from '../Oracle/IOracle.sol'; import {ICurve} from '../Curves/ICurve.sol'; import {Math} from '../utils/math/Math.sol'; import {IBondingCurve} from '../Curves/IBondingCurve.sol'; /** * @title ARTHStablecoin. * @author MahaDAO. */ contract ArthController is AccessControl, IARTHController { using SafeMath for uint256; IERC20 public ARTH; IERC20 public ARTHX; IERC20 public MAHA; IUniswapPairOracle public MAHAGMUOracle; IUniswapPairOracle public ARTHXGMUOracle; ICurve public recollateralizeDiscountCruve; IBondingCurve public bondingCurve; address public ownerAddress; address public timelockAddress; address public DEFAULT_ADMIN_ADDRESS; uint256 public globalCollateralRatio; uint256 public collateralRaisedOnOtherChain = 0; uint256 public override buybackFee; // 6 decimals of precision, divide by 1000000 in calculations for fee. uint256 public override mintingFee; uint256 public override redemptionFee; uint256 public maxRecollateralizeDiscount = 750000; // In 1e6 precision. /// @notice Timestamp at which contract was deployed. uint256 public immutable genesisTimestamp; /// @notice Will use uniswap oracle after this duration. uint256 public constant maxGenesisDuration = 7 days; /// @notice Will force use of genesis oracle during genesis. bool public isARTHXGenesActive = true; bool public isColalteralRatioPaused = false; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256('COLLATERAL_RATIO_PAUSER'); bytes32 public constant _RECOLLATERALIZE_PAUSER = keccak256('RECOLLATERALIZE_PAUSER'); bytes32 public constant _MINT_PAUSER = keccak256('MINT_PAUSER'); bytes32 public constant _REDEEM_PAUSER = keccak256('REDEEM_PAUSER'); bytes32 public constant _BUYBACK_PAUSER = keccak256('BUYBACK_PAUSER'); address[] public arthPoolsArray; // These contracts are able to mint ARTH. mapping(address => bool) public override arthPools; bool public mintPaused = false; bool public redeemPaused = false; bool public buyBackPaused = true; bool public recollateralizePaused = true; uint256 public constant _PRICE_PRECISION = 1e6; uint256 public stabilityFee = 0; // 1e4; // 1% in e6 precision. event TargetPriceChanged(uint256 old, uint256 current); event RedemptionFeeChanged(uint256 old, uint256 current); event MintingFeeChanged(uint256 old, uint256 current); /** * Modifiers. */ modifier onlyCollateralRatioPauser() { require( hasRole(COLLATERAL_RATIO_PAUSER, msg.sender), 'ARTHController: FORBIDDEN' ); _; } modifier onlyAdmin() { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'ARTHController: FORBIDDEN' ); _; } modifier onlyByOwnerOrGovernance() { require( msg.sender == ownerAddress || msg.sender == timelockAddress, 'ARTHController: FORBIDDEN' ); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == ownerAddress || msg.sender == timelockAddress || arthPools[msg.sender], 'ARTHController: FORBIDDEN' ); _; } /** * Constructor. */ constructor( IERC20 _arth, IERC20 _arthx, IERC20 _maha, address _owner, address _timelockAddress ) { ARTH = _arth; MAHA = _maha; ARTHX = _arthx; timelockAddress = _timelockAddress; DEFAULT_ADMIN_ADDRESS = _msgSender(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(COLLATERAL_RATIO_PAUSER, timelockAddress); globalCollateralRatio = 11e5; grantRole(_MINT_PAUSER, _timelockAddress); grantRole(_REDEEM_PAUSER, _timelockAddress); grantRole(_BUYBACK_PAUSER, _timelockAddress); grantRole(_RECOLLATERALIZE_PAUSER, _timelockAddress); genesisTimestamp = block.timestamp; ownerAddress = _owner; } /** * External. */ function deactivateGenesis() external onlyByOwnerOrGovernance { isARTHXGenesActive = false; } function setBondingCurve(IBondingCurve curve) external onlyByOwnerOrGovernance { bondingCurve = curve; } function setRecollateralizationCurve(ICurve curve) external onlyByOwnerGovernanceOrPool { recollateralizeDiscountCruve = curve; } /// @notice Adds collateral addresses supported. /// @dev Collateral must be an ERC20. function addPool(address poolAddress) external override onlyByOwnerOrGovernance { require(!arthPools[poolAddress], 'ARTHController: address present'); arthPools[poolAddress] = true; arthPoolsArray.push(poolAddress); } function addPools(address[] memory poolAddress) external override onlyByOwnerOrGovernance { for (uint256 index = 0; index < poolAddress.length; index++) { arthPools[poolAddress[index]] = true; arthPoolsArray.push(poolAddress[index]); } } function removePool(address poolAddress) external override onlyByOwnerOrGovernance { require(arthPools[poolAddress], 'ARTHController: address absent'); // Delete from the mapping. delete arthPools[poolAddress]; uint256 noOfPools = arthPoolsArray.length; // 'Delete' from the array by setting the address to 0x0 for (uint256 i = 0; i < noOfPools; i++) { if (arthPoolsArray[i] == poolAddress) { arthPoolsArray[i] = address(0); // This will leave a null in the array and keep the indices the same. break; } } } function setGlobalCollateralRatio(uint256 _globalCollateralRatio) external override onlyAdmin { globalCollateralRatio = _globalCollateralRatio; } function setStabilityFee(uint256 percent) external override onlyByOwnerOrGovernance { require(percent <= 1e6, 'ArthPool: percent > 1e6'); stabilityFee = percent; } function setARTHXGMUOracle(address _arthxOracleAddress) external override onlyByOwnerOrGovernance { ARTHXGMUOracle = IUniswapPairOracle(_arthxOracleAddress); } function setMAHAGMUOracle(address oracle) external override onlyByOwnerOrGovernance { MAHAGMUOracle = IUniswapPairOracle(oracle); } function setFeesParameters( uint256 _mintingFee, uint256 _buybackFee, uint256 _redemptionFee ) external override onlyByOwnerOrGovernance { mintingFee = _mintingFee; buybackFee = _buybackFee; redemptionFee = _redemptionFee; } function toggleCollateralRatio() external override onlyCollateralRatioPauser { isColalteralRatioPaused = !isColalteralRatioPaused; } function setMintingFee(uint256 fee) external override onlyByOwnerOrGovernance { uint256 old = mintingFee; mintingFee = fee; emit MintingFeeChanged(old, mintingFee); } function setRedemptionFee(uint256 fee) external override onlyByOwnerOrGovernance { uint256 old = redemptionFee; redemptionFee = fee; emit RedemptionFeeChanged(old, redemptionFee); } function setBuybackFee(uint256 fee) external override onlyByOwnerOrGovernance { buybackFee = fee; } function setOwner(address _ownerAddress) external override onlyByOwnerOrGovernance { ownerAddress = _ownerAddress; } function setGlobalColletaralValue(uint256 _collateralRaised) public onlyAdmin { collateralRaisedOnOtherChain = _collateralRaised; } function setTimelock(address newTimelock) external override onlyByOwnerOrGovernance { timelockAddress = newTimelock; } function getMAHAPrice() public view override returns (uint256) { return MAHAGMUOracle.consult(address(MAHA), _PRICE_PRECISION); } function getARTHXPrice() public view override returns (uint256) { if (getIsGenesisActive()) return getARTHXGenesisPrice(); return ARTHXGMUOracle.consult(address(ARTHX), _PRICE_PRECISION); } function getIsGenesisActive() public view override returns (bool) { return (isARTHXGenesActive && block.timestamp.sub(genesisTimestamp) <= maxGenesisDuration); } function getARTHXGenesisPrice() public pure override returns (uint256) { return 1e4; } function getARTHXGenesisDiscount() external view override returns (uint256) { return bondingCurve.getY(getPercentCollateralized()); } function getGlobalCollateralRatio() public view override returns (uint256) { return globalCollateralRatio; } function getGlobalCollateralValue() public view override returns (uint256) { uint256 totalCollateralValueD18 = 0; uint256 noOfPools = arthPoolsArray.length; for (uint256 i = 0; i < noOfPools; i++) { // Exclude null addresses. if (arthPoolsArray[i] != address(0)) { totalCollateralValueD18 = totalCollateralValueD18.add( IARTHPool(arthPoolsArray[i]).getCollateralGMUBalance() ); } } return totalCollateralValueD18.add(collateralRaisedOnOtherChain); } function getARTHSupply() public view override returns (uint256) { return ARTH.totalSupply(); } function getMintingFee() external view override returns (uint256) { return mintingFee; } function getBuybackFee() external view override returns (uint256) { return buybackFee; } function getRedemptionFee() external view override returns (uint256) { return redemptionFee; } function getTargetCollateralValue() public view override returns (uint256) { return getARTHSupply().mul(getGlobalCollateralRatio()).div(1e6); } function getPercentCollateralized() public view override returns (uint256) { uint256 targetCollatValue = getTargetCollateralValue(); uint256 currentCollatValue = getGlobalCollateralValue(); return currentCollatValue.mul(1e18).div(targetCollatValue); } function getRecollateralizationDiscount() public view override returns (uint256) { return Math.min( recollateralizeDiscountCruve .getY(getPercentCollateralized()) .mul(_PRICE_PRECISION) .div(100), maxRecollateralizeDiscount ); } function getARTHInfo() external view override returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256, // uint256, uint256 ) { return ( 0, // getARTHPrice(), // ARTH price. getARTHXPrice(), // ARTHX price. ARTH.totalSupply(), // ARTH total supply. globalCollateralRatio, // Global collateralization ratio. getGlobalCollateralValue(), // Global collateral value. mintingFee, // Minting fee. redemptionFee, // Redemtion fee. // getETHGMUPrice(), // ETH/GMU price. buybackFee ); } function toggleMinting() external override { require(hasRole(_MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; } function toggleRedeeming() external override { require(hasRole(_REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; } function toggleRecollateralize() external override { require(hasRole(_RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; } function toggleBuyBack() external override { require(hasRole(_BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; } function isRedeemPaused() external view override returns (bool) { if (getIsGenesisActive()) return true; return redeemPaused; } function isMintPaused() external view override returns (bool) { if (getIsGenesisActive()) return true; return mintPaused; } function isBuybackPaused() external view override returns (bool) { return buyBackPaused; } function isRecollaterlizePaused() external view override returns (bool) { return recollateralizePaused; } function getStabilityFee() external view override returns (uint256) { if (getIsGenesisActive()) return 0; return stabilityFee; } function isPool(address pool) external view override returns (bool) { return arthPools[pool]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; interface IARTHController { function toggleCollateralRatio() external; function addPool(address pool_address) external; function addPools(address[] memory poolAddress) external; function removePool(address pool_address) external; function getARTHSupply() external view returns (uint256); function isPool(address pool) external view returns (bool); function getARTHInfo() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256, // uint256, uint256 ); function setMintingFee(uint256 fee) external; function setMAHAGMUOracle(address oracle) external; function setARTHXGMUOracle(address _arthxOracleAddress) external; function setFeesParameters( uint256 _mintingFee, uint256 _buybackFee, uint256 _redemptionFee ) external; function setRedemptionFee(uint256 fee) external; function setBuybackFee(uint256 fee) external; function setOwner(address _ownerAddress) external; function setTimelock(address newTimelock) external; function setGlobalCollateralRatio(uint256 _globalCollateralRatio) external; function getARTHXPrice() external view returns (uint256); function getMintingFee() external view returns (uint256); function getMAHAPrice() external view returns (uint256); function getBuybackFee() external view returns (uint256); function getRedemptionFee() external view returns (uint256); function getGlobalCollateralRatio() external view returns (uint256); function getARTHXGenesisDiscount() external view returns (uint256); function getGlobalCollateralValue() external view returns (uint256); function arthPools(address pool) external view returns (bool); function setStabilityFee(uint256 val) external; function isRedeemPaused() external view returns (bool); function isMintPaused() external view returns (bool); function isBuybackPaused() external view returns (bool); function isRecollaterlizePaused() external view returns (bool); function toggleMinting() external; function toggleRedeeming() external; function toggleRecollateralize() external; function toggleBuyBack() external; function getStabilityFee() external view returns (uint256); // todo add this here function mintingFee() external returns (uint256); function redemptionFee() external returns (uint256); function buybackFee() external returns (uint256); function getRecollateralizationDiscount() external returns (uint256); function getIsGenesisActive() external view returns (bool); function getARTHXGenesisPrice() external view returns (uint256); function getTargetCollateralValue() external view returns (uint256); function getPercentCollateralized() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IARTHPool { function repay(uint256 amount) external; function borrow(uint256 amount) external; function setBuyBackCollateralBuffer(uint256 percent) external; function setCollatGMUOracle(address _collateralGMUOracleAddress) external; function setPoolParameters(uint256 newCeiling, uint256 newRedemptionDelay) external; function setTimelock(address newTimelock) external; function setOwner(address ownerAddress) external; function mint(uint256 collateralAmount, uint256 arthOutMin, uint256 arthxOutMin) external returns (uint256, uint256); function redeem(uint256 arthAmount, uint256 arthxAmount, uint256 collateralOutMin) external; function collectRedemption() external; function recollateralizeARTH(uint256 collateralAmount, uint256 arthxOutMin) external returns (uint256); function buyBackARTHX(uint256 arthxAmount, uint256 collateralOutMin) external; function getGlobalCR() external view returns (uint256); function getCollateralGMUBalance() external view returns (uint256); function getAvailableExcessCollateralDV() external view returns (uint256); function getCollateralPrice() external view returns (uint256); function collateralGMUOracleAddress() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ICurve} from './ICurve.sol'; interface IBondingCurve is ICurve { function getFixedPrice() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ICurve { function getY(uint256 x) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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 number of decimals for token. */ function decimals() external view returns (uint8); /** * @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; interface IOracle { function getPrice() external view returns (uint256); function getDecimalPercision() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapPairOracle { function update() external; function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); function canUpdate() external view returns (bool); } // 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 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); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // 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. 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; } } }
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); }
580,379
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../interfaces/yearn/IController.sol"; import "../interfaces/yearn/IVault.sol"; /// @title yVault yAgnostic. /// @dev yVault inherits ERC20. contract yVault is IVault, ERC20, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /// @notice Underlying token the vault operates with. /// @dev Set in constructor. /// @return Underlying token the vault operates with. address public override token; /// @notice Displays percentage to calculate available. /// @dev By default: 9500(95%). /// @return Percentage to calculate available. uint256 public min = 9500; /// @notice Displays percentage to calculate available. /// @dev By default: 10000(100%). /// @return Percentage to calculate available. uint256 public constant MAX = 10000; /// @notice Variable storing the governance address. By default it is equal to the deployer of the controller. /// @dev Specified when creating the controller (in the constructor). /// @dev Can also be changed using the setGovernance method. /// @return Returns the governance address of this contract. address public override governance; /// @notice Variable storing the controller address. /// @notice By default, it is equal to the address specified during deployment. /// @dev Specified when creating the controller (in the constructor). /// @dev Can also be changed using the setController method. /// @return Returns the controller address of this contract. address public override controller; /// @notice Modifier to restrict the method for governance only. modifier governanceOnly() { require(_msgSender() == governance, "Not the governance"); _; } /// @notice Modifier to restrict the method for controller only. modifier controllerOnly() { require(_msgSender() == controller, "Not the controller"); _; } /// @notice Sets token name: yfiag + name, token symbol: y + symbol. /// @notice Sets the governance address equal to the deployer. /// @param _token Address of the token the vault work with. /// @param _controller Address of the controller. constructor(address _token, address _controller) public ERC20( string(abi.encodePacked("yfiag ", ERC20(_token).name())), string(abi.encodePacked("y", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = _token; governance = _msgSender(); controller = _controller; } /****** * Governance regulated parameters ******/ /// @notice called by the owner to pause, triggers stopped state function pause() whenNotPaused governanceOnly external { _pause(); } /// @notice called by the owner to unpause, returns to normal state function unpause() whenPaused governanceOnly external { _unpause(); } /// @notice Set percentage of tokens allowed for the strategy. /// @dev Can only be called by governance. The maximum value is 10000(100%). /// @param _min Percentage to calculate available. function setMin(uint256 _min) external governanceOnly { require(_min <= MAX, "min<=max"); min = _min; } /// @notice Specifies a new governance address. /// @dev Can only be called by governance. /// @param _governance Address of the new governance. function setGovernance(address _governance) external governanceOnly { governance = _governance; } /// @notice Specifies a new controller address. /// @dev Can only be called by governance. /// @param _controller Address of the new controller. function setController(address _controller) external governanceOnly { controller = _controller; } /****** * Vault functionality ******/ /// @notice Method transferring tokens to a strategy through controller. function earn() whenNotPaused external { uint256 _bal = available(); IERC20(token).safeTransfer(controller, _bal); IController(controller).earn(address(this), address(token), _bal); } /// @notice Used to swap any borrowed reserve over the debt limit to liquidate to underlying 'token' /// @param reserve Address of the reserve token. /// @param amount Amount of the tokens. function harvest(address reserve, uint256 amount) external controllerOnly { require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } /// @notice Causes the deposit of all available sender tokens. function depositAll() whenNotPaused external override { deposit(IERC20(token).balanceOf(_msgSender())); } /// @notice Causes the deposit of amount sender tokens. /// @param _amount Amount of the tokens. function deposit(uint256 _amount) whenNotPaused nonReentrant public override { uint256 _pool = balance(); uint256 _before = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransferFrom(_msgSender(), address(this), _amount); uint256 _after = IERC20(token).balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(_msgSender(), shares); } /// @notice Causes the withdraw of all available sender shares. function withdrawAll() whenNotPaused external override { withdraw(balanceOf(_msgSender())); } // No rebalance implementation for lower fees and faster swaps /// @notice Causes the withdraw of amount sender shares. /// @param _shares Amount of the shares. function withdraw(uint256 _shares) whenNotPaused public override { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(_msgSender(), _shares); // Check balance uint256 b = IERC20(token).balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(_withdraw); uint256 _after = IERC20(token).balanceOf(address(this)); require(_after >= r, "Not enough balance"); } IERC20(token).safeTransfer(_msgSender(), r); } /***** * View interface *****/ /// @notice Сalculates the price per full share. /// @return Returns the price per full share. function getPricePerFullShare() external view override returns (uint256) { return balance().mul(1e18).div(totalSupply()); } /// @notice Shows how many tokens are available (in total in the volt and deposited to the strategy). function balance() public view returns (uint256) { return IERC20(token).balanceOf(address(this)).add(IController(controller).balanceOf(address(this))); } /// @notice Сalculates the available amount that can be transferred to the strategy. /// @dev Custom logic in here for how much the vault allows to be borrowed /// @dev Sets minimum required on-hand to keep small withdrawals cheap /// @return Returns the available vault. function available() public view returns (uint256) { return IERC20(token).balanceOf(address(this)).mul(min).div(MAX); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./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 () internal { _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.6.0 <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 () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IController { function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); function earn(address, address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function tokens(address) external view returns (address); function strategies(address) external view returns (address); function approvedStrategies(address, address) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IVault { function token() external view returns (address); function controller() external view returns (address); function governance() external view returns (address); function getPricePerFullShare() external view returns (uint256); function deposit(uint256) external; function depositAll() external; function withdraw(uint256) external; function withdrawAll() external; // Part of ERC20 interface //function name() external view returns (string memory); //function symbol() external view returns (string memory); //function decimals() external view returns (uint8); } // 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; } }
Сalculates the available amount that can be transferred to the strategy. Custom logic in here for how much the vault allows to be borrowed Sets minimum required on-hand to keep small withdrawals cheap return Returns the available vault.
function available() public view returns (uint256) { return IERC20(token).balanceOf(address(this)).mul(min).div(MAX); }
5,948,792
./partial_match/4/0x3EAc0f24DeC1160B05BC780eb23d72D6B9aC48a3/sources/FaucetV1.sol
Returns maxFreeWithdraw amount./
function maxFreeWithdraw() external override view returns(uint256) { return _maxFreeWithdraw; }
8,542,702
./full_match/84531/0xF03714a8C084EE547758038A6e9a54F5f082B118/sources/BaseOptiChildsContract.sol
/ ALLOWLIST MINTING FUNCTIONS Mints tokens to an address using an allowlist. fee may or may not be required _to address of the future owner of the token _amount number of tokens to mint _merkleProof merkle proof array/
function mintToMultipleAL(address _to, uint256 _amount, bytes32[] calldata _merkleProof) public payable { if(onlyERC20MintingMode) revert OnlyERC20MintingEnabled(); if(!onlyAllowlistMode || !mintingOpen) revert AllowlistMintClosed(); if(!isAllowlisted(_to, _merkleProof)) revert AddressNotAllowlisted(); if(_amount == 0) revert MintZeroQuantity(); if(_amount > maxBatchSize) revert TransactionCapExceeded(); if(!canMintAmount(_to, _amount)) revert ExcessiveOwnedMints(); if(currentTokenId() + _amount > collectionSize) revert CapExceeded(); if(!priceIsRight(msg.value, getPrice(_amount))) revert InvalidPayment(); _safeMint(_to, _amount, false); }
14,301,864