contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AccessControlledAggregator | FluxAggregator.sol | 0xb8169f6d97c66c50ef27b7b1b3fb2875d2b036a4 | Solidity | FluxAggregator | contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 constant private RESERVE_ROUNDS = 2;
uint256 constant private MAX_ORACLE_COUNT = 77;
uint32 constant private ROUND_MAX = 2**32-1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(
uint256 indexed amount
);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(
address indexed oracle,
address indexed newAdmin
);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission)
external
{
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
onlyOwner()
{
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
{
uint32 oracleNum = oracleCount(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment");
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds()
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds()
external
view
returns (uint128)
{
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(address _oracle, address _recipient, uint256 _amount)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.transfer(_recipient, _amount), "token transfer failed");
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle)
external
view
returns (address)
{
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle)
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId)
private
{
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (validateOracleRound(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (details[_roundId].submissions.length < details[_roundId].minSubmissions) {
return (false, 0);
}
int256 newAnswer = Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function payOracle(uint32 _roundId)
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId)
private
{
require(acceptingSubmissions(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId)
private
{
if (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return;
delete details[_roundId];
}
function timedOut(uint32 _roundId)
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment)
private
view
returns (uint256)
{
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(
address _oracle,
address _admin
)
private
{
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(
address _oracle
)
private
{
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable";
}
function supersedable(uint32 _roundId)
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle)
private
view
returns (bool)
{
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId)
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId)
private
view
returns (bool)
{
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId)
private
view
returns (bool)
{
return _roundId <= ROUND_MAX;
}
} | /**
* @title The Prepaid Aggregator contract
* @notice Handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/ | NatSpecMultiLine | requestNewRound | function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
| /**
* @notice allows non-oracles to request a new round
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | MIT | {
"func_code_index": [
18643,
19038
]
} | 7,400 |
|
AccessControlledAggregator | FluxAggregator.sol | 0xb8169f6d97c66c50ef27b7b1b3fb2875d2b036a4 | Solidity | FluxAggregator | contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 constant private RESERVE_ROUNDS = 2;
uint256 constant private MAX_ORACLE_COUNT = 77;
uint32 constant private ROUND_MAX = 2**32-1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(
uint256 indexed amount
);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(
address indexed oracle,
address indexed newAdmin
);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission)
external
{
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
onlyOwner()
{
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
{
uint32 oracleNum = oracleCount(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment");
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds()
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds()
external
view
returns (uint128)
{
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(address _oracle, address _recipient, uint256 _amount)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.transfer(_recipient, _amount), "token transfer failed");
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle)
external
view
returns (address)
{
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle)
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId)
private
{
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (validateOracleRound(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (details[_roundId].submissions.length < details[_roundId].minSubmissions) {
return (false, 0);
}
int256 newAnswer = Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function payOracle(uint32 _roundId)
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId)
private
{
require(acceptingSubmissions(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId)
private
{
if (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return;
delete details[_roundId];
}
function timedOut(uint32 _roundId)
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment)
private
view
returns (uint256)
{
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(
address _oracle,
address _admin
)
private
{
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(
address _oracle
)
private
{
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable";
}
function supersedable(uint32 _roundId)
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle)
private
view
returns (bool)
{
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId)
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId)
private
view
returns (bool)
{
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId)
private
view
returns (bool)
{
return _roundId <= ROUND_MAX;
}
} | /**
* @title The Prepaid Aggregator contract
* @notice Handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/ | NatSpecMultiLine | setRequesterPermissions | function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
| /**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | MIT | {
"func_code_index": [
19376,
19814
]
} | 7,401 |
|
AccessControlledAggregator | FluxAggregator.sol | 0xb8169f6d97c66c50ef27b7b1b3fb2875d2b036a4 | Solidity | FluxAggregator | contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 constant private RESERVE_ROUNDS = 2;
uint256 constant private MAX_ORACLE_COUNT = 77;
uint32 constant private ROUND_MAX = 2**32-1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(
uint256 indexed amount
);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(
address indexed oracle,
address indexed newAdmin
);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission)
external
{
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
onlyOwner()
{
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
{
uint32 oracleNum = oracleCount(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment");
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds()
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds()
external
view
returns (uint128)
{
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(address _oracle, address _recipient, uint256 _amount)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.transfer(_recipient, _amount), "token transfer failed");
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle)
external
view
returns (address)
{
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle)
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId)
private
{
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (validateOracleRound(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (details[_roundId].submissions.length < details[_roundId].minSubmissions) {
return (false, 0);
}
int256 newAnswer = Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function payOracle(uint32 _roundId)
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId)
private
{
require(acceptingSubmissions(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId)
private
{
if (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return;
delete details[_roundId];
}
function timedOut(uint32 _roundId)
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment)
private
view
returns (uint256)
{
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(
address _oracle,
address _admin
)
private
{
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(
address _oracle
)
private
{
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable";
}
function supersedable(uint32 _roundId)
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle)
private
view
returns (bool)
{
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId)
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId)
private
view
returns (bool)
{
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId)
private
view
returns (bool)
{
return _roundId <= ROUND_MAX;
}
} | /**
* @title The Prepaid Aggregator contract
* @notice Handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/ | NatSpecMultiLine | onTokenTransfer | function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
| /**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | MIT | {
"func_code_index": [
20091,
20274
]
} | 7,402 |
|
AccessControlledAggregator | FluxAggregator.sol | 0xb8169f6d97c66c50ef27b7b1b3fb2875d2b036a4 | Solidity | FluxAggregator | contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 constant private RESERVE_ROUNDS = 2;
uint256 constant private MAX_ORACLE_COUNT = 77;
uint32 constant private ROUND_MAX = 2**32-1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(
uint256 indexed amount
);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(
address indexed oracle,
address indexed newAdmin
);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission)
external
{
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
onlyOwner()
{
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
{
uint32 oracleNum = oracleCount(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment");
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds()
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds()
external
view
returns (uint128)
{
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(address _oracle, address _recipient, uint256 _amount)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.transfer(_recipient, _amount), "token transfer failed");
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle)
external
view
returns (address)
{
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle)
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId)
private
{
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (validateOracleRound(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (details[_roundId].submissions.length < details[_roundId].minSubmissions) {
return (false, 0);
}
int256 newAnswer = Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function payOracle(uint32 _roundId)
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId)
private
{
require(acceptingSubmissions(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId)
private
{
if (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return;
delete details[_roundId];
}
function timedOut(uint32 _roundId)
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment)
private
view
returns (uint256)
{
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(
address _oracle,
address _admin
)
private
{
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(
address _oracle
)
private
{
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable";
}
function supersedable(uint32 _roundId)
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle)
private
view
returns (bool)
{
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId)
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId)
private
view
returns (bool)
{
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId)
private
view
returns (bool)
{
return _roundId <= ROUND_MAX;
}
} | /**
* @title The Prepaid Aggregator contract
* @notice Handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/ | NatSpecMultiLine | oracleRoundState | function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
| /**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | MIT | {
"func_code_index": [
20503,
21451
]
} | 7,403 |
|
AccessControlledAggregator | FluxAggregator.sol | 0xb8169f6d97c66c50ef27b7b1b3fb2875d2b036a4 | Solidity | FluxAggregator | contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 constant private RESERVE_ROUNDS = 2;
uint256 constant private MAX_ORACLE_COUNT = 77;
uint32 constant private ROUND_MAX = 2**32-1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(
uint256 indexed amount
);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(
address indexed oracle,
address indexed newAdmin
);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission)
external
{
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
onlyOwner()
{
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
{
uint32 oracleNum = oracleCount(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment");
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds()
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds()
external
view
returns (uint128)
{
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(address _oracle, address _recipient, uint256 _amount)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.transfer(_recipient, _amount), "token transfer failed");
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle)
external
view
returns (address)
{
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle)
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId)
private
{
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (validateOracleRound(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (details[_roundId].submissions.length < details[_roundId].minSubmissions) {
return (false, 0);
}
int256 newAnswer = Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function payOracle(uint32 _roundId)
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId)
private
{
require(acceptingSubmissions(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId)
private
{
if (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return;
delete details[_roundId];
}
function timedOut(uint32 _roundId)
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment)
private
view
returns (uint256)
{
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(
address _oracle,
address _admin
)
private
{
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(
address _oracle
)
private
{
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable";
}
function supersedable(uint32 _roundId)
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle)
private
view
returns (bool)
{
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId)
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId)
private
view
returns (bool)
{
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId)
private
view
returns (bool)
{
return _roundId <= ROUND_MAX;
}
} | /**
* @title The Prepaid Aggregator contract
* @notice Handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/ | NatSpecMultiLine | setValidator | function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
| /**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | MIT | {
"func_code_index": [
21625,
21911
]
} | 7,404 |
|
AccessControlledAggregator | FluxAggregator.sol | 0xb8169f6d97c66c50ef27b7b1b3fb2875d2b036a4 | Solidity | FluxAggregator | contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 constant private RESERVE_ROUNDS = 2;
uint256 constant private MAX_ORACLE_COUNT = 77;
uint32 constant private ROUND_MAX = 2**32-1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(
uint256 indexed amount
);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(
address indexed oracle,
address indexed newAdmin
);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission)
external
{
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
onlyOwner()
{
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
{
uint32 oracleNum = oracleCount(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment");
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds()
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds()
external
view
returns (uint128)
{
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(address _oracle, address _recipient, uint256 _amount)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.transfer(_recipient, _amount), "token transfer failed");
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle)
external
view
returns (address)
{
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle)
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId)
private
{
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (validateOracleRound(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (details[_roundId].submissions.length < details[_roundId].minSubmissions) {
return (false, 0);
}
int256 newAnswer = Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function payOracle(uint32 _roundId)
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId)
private
{
require(acceptingSubmissions(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId)
private
{
if (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return;
delete details[_roundId];
}
function timedOut(uint32 _roundId)
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment)
private
view
returns (uint256)
{
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(
address _oracle,
address _admin
)
private
{
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(
address _oracle
)
private
{
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable";
}
function supersedable(uint32 _roundId)
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle)
private
view
returns (bool)
{
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId)
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId)
private
view
returns (bool)
{
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId)
private
view
returns (bool)
{
return _roundId <= ROUND_MAX;
}
} | /**
* @title The Prepaid Aggregator contract
* @notice Handles aggregating data pushed in from off-chain, and unlocks
* payment for oracles as they report. Oracles' submissions are gathered in
* rounds, with each round aggregating the submissions for each oracle into a
* single answer. The latest aggregated answer is exposed as well as historical
* answers and their updated at timestamp.
*/ | NatSpecMultiLine | initializeNewRound | function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
| /**
* Private
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | MIT | {
"func_code_index": [
21940,
22420
]
} | 7,405 |
|
SignatureVerifier | contracts/components/Halt.sol | 0x9276ee38a5250e2f7fbe00a12ec17d09b5d28f3d | Solidity | Halt | contract Halt is Owned {
bool public halted = false;
modifier notHalted() {
require(!halted, "Smart contract is halted");
_;
}
modifier isHalted() {
require(halted, "Smart contract is not halted");
_;
}
/// @notice function Emergency situation that requires
/// @notice contribution period to stop or not.
function setHalt(bool halt)
public
onlyOwner
{
halted = halt;
}
} | setHalt | function setHalt(bool halt)
public
onlyOwner
{
halted = halt;
}
| /// @notice function Emergency situation that requires
/// @notice contribution period to stop or not. | NatSpecSingleLine | v0.4.26+commit.4563c3fc | None | bzzr://03fc2b9396bc022b54ffadd1c82ab3c4f783fcfb3b4145c66e6f16719a2bd289 | {
"func_code_index": [
386,
491
]
} | 7,406 |
||
SNN | contracts/SNN.sol | 0x09f5fe01e781536773456aafb9fee20e2fc6220e | Solidity | SNN | contract SNN is Ownable, ERC721B {
IStrongService strongService = IStrongService(0xFbdDaDD80fe7bda00B901FbAf73803F2238Ae655);
IERC20 strongToken = IERC20(0x990f341946A3fdB507aE7e52d17851B87168017c);
using Strings for uint256;
string private _tokenBaseURI;
uint256 public MAX_SNN_SUPPLY;
bool public isSale;
constructor() ERC721B("STRONG NODE NFT Test", "SNNTest") {
MAX_SNN_SUPPLY = 10000;
strongToken.approve(address(strongService), 2**256 - 1);
}
/**
* Check if certain token id is exists.
*/
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_tokenBaseURI, tokenId.toString()));
}
/**
* Get the array of token for owner.
*/
function tokensOfOwner(address owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 id = 0;
for (uint256 index = 0; index < _owners.length; index++) {
if(_owners[index] == owner)
result[id++] = index;
}
return result;
}
}
function getRewardByBlock(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
return strongService.getRewardByBlock(address(this), tokenId + 1, blockNumber);
}
function getReward(uint128 tokenId)
external
view
returns (uint256)
{
return strongService.getReward(address(this), tokenId + 1);
}
function getClaimFee(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
uint256 reward = getRewardByBlock(tokenId, blockNumber);
return reward * strongService.claimingFeeNumerator() / strongService.claimingFeeDenominator();
}
/*
* Set base URI
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_tokenBaseURI = baseURI;
}
/*
* Set sale status
*/
function setSaleStatus(bool _isSale) external onlyOwner {
isSale = _isSale;
}
/**
* Create Strong Node & Mint SNN
*/
function mint()
external
payable
{
require(isSale, "Sale must be active to mint");
uint256 supply = _owners.length;
uint256 naasRequestingFeeInWei = strongService.naasRequestingFeeInWei();
uint256 naasStrongFeeInWei = strongService.naasStrongFeeInWei();
require(msg.value == naasRequestingFeeInWei, "invalid requesting fee");
require(supply + 1 <= MAX_SNN_SUPPLY, "Purchase would exceed max supply");
strongToken.transferFrom(msg.sender, address(this), naasStrongFeeInWei);
strongService.requestAccess{value: naasRequestingFeeInWei}(true);
_mint( msg.sender, supply++);
}
function claim(uint128 tokenId, uint256 blockNumber)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner(), "invalid owner.");
uint256 fee = getClaimFee(tokenId, blockNumber);
require (msg.value >= fee, "invalid fee.");
uint256 oldBalance = address(this).balance - msg.value;
strongService.claim{value: msg.value}(tokenId + 1, blockNumber, false);
uint256 reward = address(this).balance - oldBalance;
payable(ownerOf(tokenId)).transfer(reward);
}
function payFee(uint128 tokenId)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner() , "invalid owner.");
require(msg.value == strongService.recurringNaaSFeeInWei(), "invalid fee");
strongService.payFee{value: msg.value}(tokenId + 1);
}
function payAll()
external
payable
{
require(msg.value == strongService.recurringNaaSFeeInWei() * _owners.length, "invalid fee");
strongService.payAll{value: msg.value}(_owners.length);
}
function getNaasRequestingFeeInWei()
external
view
returns (uint256)
{
return strongService.naasRequestingFeeInWei();
}
function getNaasStrongFeeInWei()
external
view
returns (uint256)
{
return strongService.naasStrongFeeInWei();
}
function getRecurringNaaSFeeInWei()
external
view
returns (uint256)
{
return strongService.recurringNaaSFeeInWei();
}
} | /**
* @title SNN contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/ | NatSpecMultiLine | exists | function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
| /**
* Check if certain token id is exists.
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | {
"func_code_index": [
561,
667
]
} | 7,407 |
||
SNN | contracts/SNN.sol | 0x09f5fe01e781536773456aafb9fee20e2fc6220e | Solidity | SNN | contract SNN is Ownable, ERC721B {
IStrongService strongService = IStrongService(0xFbdDaDD80fe7bda00B901FbAf73803F2238Ae655);
IERC20 strongToken = IERC20(0x990f341946A3fdB507aE7e52d17851B87168017c);
using Strings for uint256;
string private _tokenBaseURI;
uint256 public MAX_SNN_SUPPLY;
bool public isSale;
constructor() ERC721B("STRONG NODE NFT Test", "SNNTest") {
MAX_SNN_SUPPLY = 10000;
strongToken.approve(address(strongService), 2**256 - 1);
}
/**
* Check if certain token id is exists.
*/
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_tokenBaseURI, tokenId.toString()));
}
/**
* Get the array of token for owner.
*/
function tokensOfOwner(address owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 id = 0;
for (uint256 index = 0; index < _owners.length; index++) {
if(_owners[index] == owner)
result[id++] = index;
}
return result;
}
}
function getRewardByBlock(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
return strongService.getRewardByBlock(address(this), tokenId + 1, blockNumber);
}
function getReward(uint128 tokenId)
external
view
returns (uint256)
{
return strongService.getReward(address(this), tokenId + 1);
}
function getClaimFee(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
uint256 reward = getRewardByBlock(tokenId, blockNumber);
return reward * strongService.claimingFeeNumerator() / strongService.claimingFeeDenominator();
}
/*
* Set base URI
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_tokenBaseURI = baseURI;
}
/*
* Set sale status
*/
function setSaleStatus(bool _isSale) external onlyOwner {
isSale = _isSale;
}
/**
* Create Strong Node & Mint SNN
*/
function mint()
external
payable
{
require(isSale, "Sale must be active to mint");
uint256 supply = _owners.length;
uint256 naasRequestingFeeInWei = strongService.naasRequestingFeeInWei();
uint256 naasStrongFeeInWei = strongService.naasStrongFeeInWei();
require(msg.value == naasRequestingFeeInWei, "invalid requesting fee");
require(supply + 1 <= MAX_SNN_SUPPLY, "Purchase would exceed max supply");
strongToken.transferFrom(msg.sender, address(this), naasStrongFeeInWei);
strongService.requestAccess{value: naasRequestingFeeInWei}(true);
_mint( msg.sender, supply++);
}
function claim(uint128 tokenId, uint256 blockNumber)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner(), "invalid owner.");
uint256 fee = getClaimFee(tokenId, blockNumber);
require (msg.value >= fee, "invalid fee.");
uint256 oldBalance = address(this).balance - msg.value;
strongService.claim{value: msg.value}(tokenId + 1, blockNumber, false);
uint256 reward = address(this).balance - oldBalance;
payable(ownerOf(tokenId)).transfer(reward);
}
function payFee(uint128 tokenId)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner() , "invalid owner.");
require(msg.value == strongService.recurringNaaSFeeInWei(), "invalid fee");
strongService.payFee{value: msg.value}(tokenId + 1);
}
function payAll()
external
payable
{
require(msg.value == strongService.recurringNaaSFeeInWei() * _owners.length, "invalid fee");
strongService.payAll{value: msg.value}(_owners.length);
}
function getNaasRequestingFeeInWei()
external
view
returns (uint256)
{
return strongService.naasRequestingFeeInWei();
}
function getNaasStrongFeeInWei()
external
view
returns (uint256)
{
return strongService.naasStrongFeeInWei();
}
function getRecurringNaaSFeeInWei()
external
view
returns (uint256)
{
return strongService.recurringNaaSFeeInWei();
}
} | /**
* @title SNN contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/ | NatSpecMultiLine | tokensOfOwner | function tokensOfOwner(address owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 id = 0;
for (uint256 index = 0; index < _owners.length; index++) {
if(_owners[index] == owner)
result[id++] = index;
}
return result;
}
}
| /**
* Get the array of token for owner.
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | {
"func_code_index": [
991,
1509
]
} | 7,408 |
||
SNN | contracts/SNN.sol | 0x09f5fe01e781536773456aafb9fee20e2fc6220e | Solidity | SNN | contract SNN is Ownable, ERC721B {
IStrongService strongService = IStrongService(0xFbdDaDD80fe7bda00B901FbAf73803F2238Ae655);
IERC20 strongToken = IERC20(0x990f341946A3fdB507aE7e52d17851B87168017c);
using Strings for uint256;
string private _tokenBaseURI;
uint256 public MAX_SNN_SUPPLY;
bool public isSale;
constructor() ERC721B("STRONG NODE NFT Test", "SNNTest") {
MAX_SNN_SUPPLY = 10000;
strongToken.approve(address(strongService), 2**256 - 1);
}
/**
* Check if certain token id is exists.
*/
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_tokenBaseURI, tokenId.toString()));
}
/**
* Get the array of token for owner.
*/
function tokensOfOwner(address owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 id = 0;
for (uint256 index = 0; index < _owners.length; index++) {
if(_owners[index] == owner)
result[id++] = index;
}
return result;
}
}
function getRewardByBlock(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
return strongService.getRewardByBlock(address(this), tokenId + 1, blockNumber);
}
function getReward(uint128 tokenId)
external
view
returns (uint256)
{
return strongService.getReward(address(this), tokenId + 1);
}
function getClaimFee(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
uint256 reward = getRewardByBlock(tokenId, blockNumber);
return reward * strongService.claimingFeeNumerator() / strongService.claimingFeeDenominator();
}
/*
* Set base URI
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_tokenBaseURI = baseURI;
}
/*
* Set sale status
*/
function setSaleStatus(bool _isSale) external onlyOwner {
isSale = _isSale;
}
/**
* Create Strong Node & Mint SNN
*/
function mint()
external
payable
{
require(isSale, "Sale must be active to mint");
uint256 supply = _owners.length;
uint256 naasRequestingFeeInWei = strongService.naasRequestingFeeInWei();
uint256 naasStrongFeeInWei = strongService.naasStrongFeeInWei();
require(msg.value == naasRequestingFeeInWei, "invalid requesting fee");
require(supply + 1 <= MAX_SNN_SUPPLY, "Purchase would exceed max supply");
strongToken.transferFrom(msg.sender, address(this), naasStrongFeeInWei);
strongService.requestAccess{value: naasRequestingFeeInWei}(true);
_mint( msg.sender, supply++);
}
function claim(uint128 tokenId, uint256 blockNumber)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner(), "invalid owner.");
uint256 fee = getClaimFee(tokenId, blockNumber);
require (msg.value >= fee, "invalid fee.");
uint256 oldBalance = address(this).balance - msg.value;
strongService.claim{value: msg.value}(tokenId + 1, blockNumber, false);
uint256 reward = address(this).balance - oldBalance;
payable(ownerOf(tokenId)).transfer(reward);
}
function payFee(uint128 tokenId)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner() , "invalid owner.");
require(msg.value == strongService.recurringNaaSFeeInWei(), "invalid fee");
strongService.payFee{value: msg.value}(tokenId + 1);
}
function payAll()
external
payable
{
require(msg.value == strongService.recurringNaaSFeeInWei() * _owners.length, "invalid fee");
strongService.payAll{value: msg.value}(_owners.length);
}
function getNaasRequestingFeeInWei()
external
view
returns (uint256)
{
return strongService.naasRequestingFeeInWei();
}
function getNaasStrongFeeInWei()
external
view
returns (uint256)
{
return strongService.naasStrongFeeInWei();
}
function getRecurringNaaSFeeInWei()
external
view
returns (uint256)
{
return strongService.recurringNaaSFeeInWei();
}
} | /**
* @title SNN contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/ | NatSpecMultiLine | setBaseURI | function setBaseURI(string memory baseURI) external onlyOwner {
_tokenBaseURI = baseURI;
}
| /*
* Set base URI
*/ | Comment | v0.8.0+commit.c7dfd78e | {
"func_code_index": [
2246,
2352
]
} | 7,409 |
||
SNN | contracts/SNN.sol | 0x09f5fe01e781536773456aafb9fee20e2fc6220e | Solidity | SNN | contract SNN is Ownable, ERC721B {
IStrongService strongService = IStrongService(0xFbdDaDD80fe7bda00B901FbAf73803F2238Ae655);
IERC20 strongToken = IERC20(0x990f341946A3fdB507aE7e52d17851B87168017c);
using Strings for uint256;
string private _tokenBaseURI;
uint256 public MAX_SNN_SUPPLY;
bool public isSale;
constructor() ERC721B("STRONG NODE NFT Test", "SNNTest") {
MAX_SNN_SUPPLY = 10000;
strongToken.approve(address(strongService), 2**256 - 1);
}
/**
* Check if certain token id is exists.
*/
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_tokenBaseURI, tokenId.toString()));
}
/**
* Get the array of token for owner.
*/
function tokensOfOwner(address owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 id = 0;
for (uint256 index = 0; index < _owners.length; index++) {
if(_owners[index] == owner)
result[id++] = index;
}
return result;
}
}
function getRewardByBlock(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
return strongService.getRewardByBlock(address(this), tokenId + 1, blockNumber);
}
function getReward(uint128 tokenId)
external
view
returns (uint256)
{
return strongService.getReward(address(this), tokenId + 1);
}
function getClaimFee(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
uint256 reward = getRewardByBlock(tokenId, blockNumber);
return reward * strongService.claimingFeeNumerator() / strongService.claimingFeeDenominator();
}
/*
* Set base URI
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_tokenBaseURI = baseURI;
}
/*
* Set sale status
*/
function setSaleStatus(bool _isSale) external onlyOwner {
isSale = _isSale;
}
/**
* Create Strong Node & Mint SNN
*/
function mint()
external
payable
{
require(isSale, "Sale must be active to mint");
uint256 supply = _owners.length;
uint256 naasRequestingFeeInWei = strongService.naasRequestingFeeInWei();
uint256 naasStrongFeeInWei = strongService.naasStrongFeeInWei();
require(msg.value == naasRequestingFeeInWei, "invalid requesting fee");
require(supply + 1 <= MAX_SNN_SUPPLY, "Purchase would exceed max supply");
strongToken.transferFrom(msg.sender, address(this), naasStrongFeeInWei);
strongService.requestAccess{value: naasRequestingFeeInWei}(true);
_mint( msg.sender, supply++);
}
function claim(uint128 tokenId, uint256 blockNumber)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner(), "invalid owner.");
uint256 fee = getClaimFee(tokenId, blockNumber);
require (msg.value >= fee, "invalid fee.");
uint256 oldBalance = address(this).balance - msg.value;
strongService.claim{value: msg.value}(tokenId + 1, blockNumber, false);
uint256 reward = address(this).balance - oldBalance;
payable(ownerOf(tokenId)).transfer(reward);
}
function payFee(uint128 tokenId)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner() , "invalid owner.");
require(msg.value == strongService.recurringNaaSFeeInWei(), "invalid fee");
strongService.payFee{value: msg.value}(tokenId + 1);
}
function payAll()
external
payable
{
require(msg.value == strongService.recurringNaaSFeeInWei() * _owners.length, "invalid fee");
strongService.payAll{value: msg.value}(_owners.length);
}
function getNaasRequestingFeeInWei()
external
view
returns (uint256)
{
return strongService.naasRequestingFeeInWei();
}
function getNaasStrongFeeInWei()
external
view
returns (uint256)
{
return strongService.naasStrongFeeInWei();
}
function getRecurringNaaSFeeInWei()
external
view
returns (uint256)
{
return strongService.recurringNaaSFeeInWei();
}
} | /**
* @title SNN contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/ | NatSpecMultiLine | setSaleStatus | function setSaleStatus(bool _isSale) external onlyOwner {
isSale = _isSale;
}
| /*
* Set sale status
*/ | Comment | v0.8.0+commit.c7dfd78e | {
"func_code_index": [
2390,
2483
]
} | 7,410 |
||
SNN | contracts/SNN.sol | 0x09f5fe01e781536773456aafb9fee20e2fc6220e | Solidity | SNN | contract SNN is Ownable, ERC721B {
IStrongService strongService = IStrongService(0xFbdDaDD80fe7bda00B901FbAf73803F2238Ae655);
IERC20 strongToken = IERC20(0x990f341946A3fdB507aE7e52d17851B87168017c);
using Strings for uint256;
string private _tokenBaseURI;
uint256 public MAX_SNN_SUPPLY;
bool public isSale;
constructor() ERC721B("STRONG NODE NFT Test", "SNNTest") {
MAX_SNN_SUPPLY = 10000;
strongToken.approve(address(strongService), 2**256 - 1);
}
/**
* Check if certain token id is exists.
*/
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_tokenBaseURI, tokenId.toString()));
}
/**
* Get the array of token for owner.
*/
function tokensOfOwner(address owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 id = 0;
for (uint256 index = 0; index < _owners.length; index++) {
if(_owners[index] == owner)
result[id++] = index;
}
return result;
}
}
function getRewardByBlock(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
return strongService.getRewardByBlock(address(this), tokenId + 1, blockNumber);
}
function getReward(uint128 tokenId)
external
view
returns (uint256)
{
return strongService.getReward(address(this), tokenId + 1);
}
function getClaimFee(uint128 tokenId, uint256 blockNumber)
public
view
returns (uint256)
{
uint256 reward = getRewardByBlock(tokenId, blockNumber);
return reward * strongService.claimingFeeNumerator() / strongService.claimingFeeDenominator();
}
/*
* Set base URI
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_tokenBaseURI = baseURI;
}
/*
* Set sale status
*/
function setSaleStatus(bool _isSale) external onlyOwner {
isSale = _isSale;
}
/**
* Create Strong Node & Mint SNN
*/
function mint()
external
payable
{
require(isSale, "Sale must be active to mint");
uint256 supply = _owners.length;
uint256 naasRequestingFeeInWei = strongService.naasRequestingFeeInWei();
uint256 naasStrongFeeInWei = strongService.naasStrongFeeInWei();
require(msg.value == naasRequestingFeeInWei, "invalid requesting fee");
require(supply + 1 <= MAX_SNN_SUPPLY, "Purchase would exceed max supply");
strongToken.transferFrom(msg.sender, address(this), naasStrongFeeInWei);
strongService.requestAccess{value: naasRequestingFeeInWei}(true);
_mint( msg.sender, supply++);
}
function claim(uint128 tokenId, uint256 blockNumber)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner(), "invalid owner.");
uint256 fee = getClaimFee(tokenId, blockNumber);
require (msg.value >= fee, "invalid fee.");
uint256 oldBalance = address(this).balance - msg.value;
strongService.claim{value: msg.value}(tokenId + 1, blockNumber, false);
uint256 reward = address(this).balance - oldBalance;
payable(ownerOf(tokenId)).transfer(reward);
}
function payFee(uint128 tokenId)
external
payable
{
require(msg.sender == ownerOf(tokenId) || msg.sender == owner() , "invalid owner.");
require(msg.value == strongService.recurringNaaSFeeInWei(), "invalid fee");
strongService.payFee{value: msg.value}(tokenId + 1);
}
function payAll()
external
payable
{
require(msg.value == strongService.recurringNaaSFeeInWei() * _owners.length, "invalid fee");
strongService.payAll{value: msg.value}(_owners.length);
}
function getNaasRequestingFeeInWei()
external
view
returns (uint256)
{
return strongService.naasRequestingFeeInWei();
}
function getNaasStrongFeeInWei()
external
view
returns (uint256)
{
return strongService.naasStrongFeeInWei();
}
function getRecurringNaaSFeeInWei()
external
view
returns (uint256)
{
return strongService.recurringNaaSFeeInWei();
}
} | /**
* @title SNN contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/ | NatSpecMultiLine | mint | function mint()
external
payable
{
require(isSale, "Sale must be active to mint");
uint256 supply = _owners.length;
uint256 naasRequestingFeeInWei = strongService.naasRequestingFeeInWei();
uint256 naasStrongFeeInWei = strongService.naasStrongFeeInWei();
require(msg.value == naasRequestingFeeInWei, "invalid requesting fee");
require(supply + 1 <= MAX_SNN_SUPPLY, "Purchase would exceed max supply");
strongToken.transferFrom(msg.sender, address(this), naasStrongFeeInWei);
strongService.requestAccess{value: naasRequestingFeeInWei}(true);
_mint( msg.sender, supply++);
}
| /**
* Create Strong Node & Mint SNN
*/ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | {
"func_code_index": [
2537,
3219
]
} | 7,411 |
||
SignatureVerifier | contracts/schnorr/SignatureVerifier.sol | 0x9276ee38a5250e2f7fbe00a12ec17d09b5d28f3d | Solidity | SignatureVerifier | contract SignatureVerifier is Halt {
/// @dev a map from a uint256 curveId to it's verifier contract address.
mapping(uint256 => address) public verifierMap;
/// @dev verify is used for check signature.
function verify(
uint256 curveId,
bytes32 signature,
bytes32 groupKeyX,
bytes32 groupKeyY,
bytes32 randomPointX,
bytes32 randomPointY,
bytes32 message
) external returns (bool) {
require(verifierMap[curveId] != address(0), "curveId not correct");
IBaseSignVerifier verifier = IBaseSignVerifier(verifierMap[curveId]);
return verifier.verify(signature, groupKeyX, groupKeyY, randomPointX, randomPointY, message);
}
function register(uint256 curveId, address verifierAddress) external onlyOwner {
verifierMap[curveId] = verifierAddress;
}
} | verify | function verify(
uint256 curveId,
bytes32 signature,
bytes32 groupKeyX,
bytes32 groupKeyY,
bytes32 randomPointX,
bytes32 randomPointY,
bytes32 message
) external returns (bool) {
require(verifierMap[curveId] != address(0), "curveId not correct");
IBaseSignVerifier verifier = IBaseSignVerifier(verifierMap[curveId]);
return verifier.verify(signature, groupKeyX, groupKeyY, randomPointX, randomPointY, message);
}
| /// @dev verify is used for check signature. | NatSpecSingleLine | v0.4.26+commit.4563c3fc | None | bzzr://03fc2b9396bc022b54ffadd1c82ab3c4f783fcfb3b4145c66e6f16719a2bd289 | {
"func_code_index": [
223,
740
]
} | 7,412 |
||
TokenERC20 | TokenERC20.sol | 0xd70e66775a74a9aedeac6e28313e1033cd726552 | Solidity | TokenERC20 | contract TokenERC20 {
/* Begin Owned Contract Members */
// An array of owners
mapping (address => bool) public owners;
// Has the next action been authorised by another owner
bool public nextActionIsAuthorised = false;
address public actionAuthorisedBy;
// Does an owner-only action have to be authorised by another owner
bool public requireAuthorisation = true;
function isOwner(address addressToCheck) view public returns (bool) {
return owners[addressToCheck];
}
modifier onlyOwners {
require(isOwner(msg.sender));
if (requireAuthorisation) {
checkActionIsAuthorisedAndReset();
}
_;
}
function authoriseNextAction() public {
require(isOwner(msg.sender));
require(requireAuthorisation);
require(!nextActionIsAuthorised);
nextActionIsAuthorised = true;
actionAuthorisedBy = msg.sender;
}
function checkActionIsAuthorisedAndReset() public {
require(isOwner(msg.sender));
bool isValidAuthorisationRequest = (nextActionIsAuthorised && actionAuthorisedBy != msg.sender);
require(isValidAuthorisationRequest);
nextActionIsAuthorised = false;
}
function setRequireAuthorisation(bool _requireAuthorisation) onlyOwners public {
requireAuthorisation = _requireAuthorisation;
}
/* End Owned Contract Members */
// Public variables of the token
bool public tokenInitialised = false;
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
uint256 public sellPrice;
address public currentSeller;
// Are users currently allowed to...
bool public allowTransfers = false; // transfer their tokens
bool public allowBurns = false; // burn their tokens
bool public allowBuying = false; // buy tokens
// This creates an array with...
mapping (address => uint256) public balanceOf; // all balances
mapping (address => uint256) public etherSpent; // how much an addeess has spent
mapping (address => bool) public frozenAccounts; // frozen accounts
address[] investors;
uint64 public investorCount;
/*** Begin ICO Variables ***/
// Unit lenghts for week, month and year
uint256 constant public weekLength = 60 * 60 * 24 * 7;
uint256 constant public monthLength = 2627856; // (60 * 60 * 24 * 30.415) As to not have to re-adjust for different month lengths
uint256 constant public yearLength = 60 * 60 * 24 * 7 * 52;
uint256 public icoBeginDate;
uint256 public icoEndDate;
bool public icoParametersSet = false;
uint256 public tokensSoldAtIco = 0;
uint256 public minimumTokenThreshold;
bool public etherHasBeenReturnedToInvestors = false;
uint256 public softCap;
uint256 public runTimeAfterSoftCapReached;
uint256 public dateSoftCapWasReached = 0;
uint256 public maxFundsThatCanBeWithdrawnByOwners = 0;
uint256 public fundsWithdrawnByOwners = 0;
uint8 immediateAllowancePercentage;
uint8 firstYearAllowancePercentage;
uint8 secondYearAllowancePercentage;
mapping (uint8 => uint8) public weekBonuses; // Bonus of 20% is stored as 120, 10% as 110 etc.
modifier onlyWhenIcoParametersAreSet {
require(icoParametersSet);
_;
}
modifier onlyWhenIcoParametersAreNotSet {
require(!icoParametersSet);
_;
}
modifier onlyDuringIco {
require(icoParametersSet);
updateContract();
require(isIcoRunning());
_;
}
/*** End ICO Variables ***/
/*** Begin ICO Setters ***/
function setIcoParametersSet(bool set) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoParametersSet = set;
}
function setIcoBeginDate(uint256 beginDate) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoBeginDate = beginDate;
}
function setIcoEndDate (uint256 endDate) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoEndDate = endDate;
}
function setSoftCap (uint256 cap) onlyWhenIcoParametersAreNotSet onlyOwners public {
softCap = cap;
}
function setRunTimeAfterSoftCapReached (uint256 runTime) onlyWhenIcoParametersAreNotSet onlyOwners public {
runTimeAfterSoftCapReached = runTime;
}
function setImmediateAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
immediateAllowancePercentage = allowancePercentage;
}
function setFirstYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
firstYearAllowancePercentage = allowancePercentage;
}
function setSecondYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
secondYearAllowancePercentage = allowancePercentage;
}
function initialiseToken() public {
require(!tokenInitialised);
name = "BaraToken";
symbol = "BRT";
totalSupply = 160000000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
currentSeller = msg.sender;
owners[msg.sender] = true;
owners[0x1434e028b12D196AcBE5304A94d0a5F816eb5d55] = true;
tokenInitialised = true;
}
function() payable public {
buyTokens();
}
function updateContract() onlyWhenIcoParametersAreSet public {
if (hasSoftCapBeenReached() && dateSoftCapWasReached == 0) {
dateSoftCapWasReached = now;
bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached > icoEndDate);
if (!reachingSoftCapWillExtendIco)
icoEndDate = dateSoftCapWasReached + runTimeAfterSoftCapReached;
}
if (!isBeforeIco())
updateOwnersWithdrawAllowance();
}
function isBeforeIco() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (now <= icoBeginDate);
}
function isIcoRunning() onlyWhenIcoParametersAreSet internal view returns (bool) {
bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached) > icoEndDate;
bool afterBeginDate = now > icoBeginDate;
bool beforeEndDate = now < icoEndDate;
if (hasSoftCapBeenReached() && !reachingSoftCapWillExtendIco)
beforeEndDate = now < (dateSoftCapWasReached + runTimeAfterSoftCapReached);
bool running = afterBeginDate && beforeEndDate;
return running;
}
function isAfterIco() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (now > icoEndDate);
}
function hasSoftCapBeenReached() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (tokensSoldAtIco >= softCap && softCap != 0);
}
// In the first week of the ICO, there will be a bonus, say 20%, then the second week 10%,
// of tokens. This retrieves that bonus. 20% is stored as 120, 10% as 110, etc.
function getWeekBonus(uint256 amountPurchased) onlyWhenIcoParametersAreSet internal view returns (uint256) {
uint256 weekBonus = uint256(weekBonuses[getWeeksPassedSinceStartOfIco()]);
if (weekBonus != 0)
return (amountPurchased * weekBonus) / 100;
return amountPurchased;
}
function getTimeSinceEndOfIco() onlyWhenIcoParametersAreSet internal view returns (uint256) {
require(now > icoEndDate);
uint256 timeSinceEndOfIco = now - icoEndDate;
return timeSinceEndOfIco;
}
function getWeeksPassedSinceStartOfIco() onlyWhenIcoParametersAreSet internal view returns (uint8) {
require(!isBeforeIco());
uint256 timeSinceIco = now - icoBeginDate;
uint8 weeksPassedSinceIco = uint8(timeSinceIco / weekLength);
return weeksPassedSinceIco;
}
// Update how much the owners can withdraw based on how much time has passed
// since the end of the ICO
function updateOwnersWithdrawAllowance() onlyWhenIcoParametersAreSet internal {
if (isAfterIco()) {
uint256 totalFunds = this.balance;
maxFundsThatCanBeWithdrawnByOwners = 0;
uint256 immediateAllowance = (totalFunds * immediateAllowancePercentage) / 100;
bool secondYear = now - icoEndDate >= yearLength;
uint8 monthsPassedSinceIco = getMonthsPassedEndOfSinceIco();
if (secondYear) {
uint256 monthsPassedInSecondYear = monthsPassedSinceIco - 12;
// (monthsPassed / 12) * (allowancePercentage / 100) i.e. (monthsPassed * allowancePercentage / 1200)
// all multiplied by the totalFunds available to be withdrwan
// They're multiplied in one line to ensure not losing any information since we don't have floats
// The minimum a person can buy is 1/10^12 tokens and we have 18 decimals, meaning always at least
// 6 decimals to hold information done in multiplication/division
uint256 secondYearAllowance = ((totalFunds * secondYearAllowancePercentage * monthsPassedInSecondYear) / 1200);
}
uint8 monthsPassedInFirstYear = monthsPassedSinceIco;
if (secondYear)
monthsPassedInFirstYear = 12;
uint256 firstYearAllowance = ((totalFunds * firstYearAllowancePercentage * monthsPassedInFirstYear) / 1200);
maxFundsThatCanBeWithdrawnByOwners = immediateAllowance + firstYearAllowance + secondYearAllowance;
}
}
function getMonthsPassedEndOfSinceIco() onlyWhenIcoParametersAreSet internal view returns (uint8) {
uint256 timePassedSinceIco = now - icoEndDate;
uint8 monthsPassedSinceIco = uint8(timePassedSinceIco / weekLength);
return monthsPassedSinceIco + 1;
}
// Check if the amount the owners are attempting to withdraw is within their current allowance
function amountIsWithinOwnersAllowance(uint256 amountToWithdraw) internal view returns (bool) {
if (now - icoEndDate >= yearLength * 2)
return true;
uint256 totalFundsWithdrawnAfterThisTransaction = fundsWithdrawnByOwners + amountToWithdraw;
bool withinAllowance = totalFundsWithdrawnAfterThisTransaction <= maxFundsThatCanBeWithdrawnByOwners;
return withinAllowance;
}
function buyTokens() onlyDuringIco payable public {
require(allowBuying);
require(!frozenAccounts[msg.sender]);
require(msg.value > 0);
uint256 numberOfTokensPurchased = msg.value / sellPrice;
require(numberOfTokensPurchased >= 10 ** 6);
numberOfTokensPurchased = getWeekBonus(numberOfTokensPurchased);
_transfer(currentSeller, msg.sender, numberOfTokensPurchased);
tokensSoldAtIco += numberOfTokensPurchased;
if (!(etherSpent[msg.sender] > 0)) {
investors[investorCount] = msg.sender;
investorCount++;
}
etherSpent[msg.sender] += msg.value;
}
/* These generate a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event FrozenFunds(address target, bool frozen);
event NewSellPrice(uint256 _sellPrice);
function setTokenName(string tokenName) onlyOwners public {
name = tokenName;
}
function setTokenSymbol(string tokenSymbol) onlyOwners public {
symbol = tokenSymbol;
}
function setAllowTransfers(bool allow) onlyOwners public {
allowTransfers = allow;
}
function setAllowBurns(bool allow) onlyOwners public {
allowBurns = allow;
}
function setAllowBuying(bool allow) onlyOwners public {
allowBuying = allow;
}
function setSellPrice(uint256 _sellPrice) onlyOwners public {
sellPrice = _sellPrice;
NewSellPrice(_sellPrice);
}
function setCurrentSeller(address newSeller) onlyOwners public {
currentSeller = newSeller;
}
function ownersTransfer(address _to, uint256 _amount) onlyOwners public {
_transfer(msg.sender, _to, _amount);
}
function transfer(address _to, uint256 _value) public {
require(allowTransfers && !isOwner(msg.sender));
_transfer(msg.sender, _to, _value);
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccounts[_from]);
require(!frozenAccounts[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwners public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function burn(uint256 amount) public {
require(allowBurns && !isOwner(msg.sender));
require(balanceOf[msg.sender] >= amount);
balanceOf[msg.sender] -= amount;
totalSupply -= amount;
Burn(msg.sender, amount);
}
function burnFrom(address from, uint256 amount) onlyOwners public {
require (balanceOf[from] >= amount);
balanceOf[from] -= amount;
totalSupply -= amount;
Burn(from, amount);
}
function freezeAccount(address target, bool freeze) onlyOwners public {
frozenAccounts[target] = freeze;
FrozenFunds(target, freeze);
}
function addOwner(address owner) onlyOwners public {
owners[owner] = true;
}
function removeOwner(address owner) onlyOwners public {
owners[owner] = false;
}
function sendContractFundsToAddress(uint256 amount, address recipient) onlyOwners public {
require(icoParametersSet);
require(isAfterIco());
require(tokensSoldAtIco >= minimumTokenThreshold);
require(amount <= this.balance);
updateContract();
require(amountIsWithinOwnersAllowance(amount));
recipient.transfer(amount);
}
function returnEtherToInvestors() onlyOwners onlyWhenIcoParametersAreSet public {
require(isAfterIco());
require(!etherHasBeenReturnedToInvestors);
require(tokensSoldAtIco < minimumTokenThreshold);
for (uint64 investorNumber; investorNumber < investorCount; investorNumber++) {
address investor = investors[investorNumber];
uint256 amountToSend = etherSpent[investor];
investor.transfer(amountToSend);
}
etherHasBeenReturnedToInvestors = true;
}
function getContractBalance() public view returns (uint256) {
return this.balance;
}
} | setIcoParametersSet | function setIcoParametersSet(bool set) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoParametersSet = set;
}
| /*** Begin ICO Setters ***/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://8626e638e1b9f4aafcab7372e5ea55969e0b4cce15dfd389fd021a12efa1b2ad | {
"func_code_index": [
3586,
3712
]
} | 7,413 |
|||
TokenERC20 | TokenERC20.sol | 0xd70e66775a74a9aedeac6e28313e1033cd726552 | Solidity | TokenERC20 | contract TokenERC20 {
/* Begin Owned Contract Members */
// An array of owners
mapping (address => bool) public owners;
// Has the next action been authorised by another owner
bool public nextActionIsAuthorised = false;
address public actionAuthorisedBy;
// Does an owner-only action have to be authorised by another owner
bool public requireAuthorisation = true;
function isOwner(address addressToCheck) view public returns (bool) {
return owners[addressToCheck];
}
modifier onlyOwners {
require(isOwner(msg.sender));
if (requireAuthorisation) {
checkActionIsAuthorisedAndReset();
}
_;
}
function authoriseNextAction() public {
require(isOwner(msg.sender));
require(requireAuthorisation);
require(!nextActionIsAuthorised);
nextActionIsAuthorised = true;
actionAuthorisedBy = msg.sender;
}
function checkActionIsAuthorisedAndReset() public {
require(isOwner(msg.sender));
bool isValidAuthorisationRequest = (nextActionIsAuthorised && actionAuthorisedBy != msg.sender);
require(isValidAuthorisationRequest);
nextActionIsAuthorised = false;
}
function setRequireAuthorisation(bool _requireAuthorisation) onlyOwners public {
requireAuthorisation = _requireAuthorisation;
}
/* End Owned Contract Members */
// Public variables of the token
bool public tokenInitialised = false;
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
uint256 public sellPrice;
address public currentSeller;
// Are users currently allowed to...
bool public allowTransfers = false; // transfer their tokens
bool public allowBurns = false; // burn their tokens
bool public allowBuying = false; // buy tokens
// This creates an array with...
mapping (address => uint256) public balanceOf; // all balances
mapping (address => uint256) public etherSpent; // how much an addeess has spent
mapping (address => bool) public frozenAccounts; // frozen accounts
address[] investors;
uint64 public investorCount;
/*** Begin ICO Variables ***/
// Unit lenghts for week, month and year
uint256 constant public weekLength = 60 * 60 * 24 * 7;
uint256 constant public monthLength = 2627856; // (60 * 60 * 24 * 30.415) As to not have to re-adjust for different month lengths
uint256 constant public yearLength = 60 * 60 * 24 * 7 * 52;
uint256 public icoBeginDate;
uint256 public icoEndDate;
bool public icoParametersSet = false;
uint256 public tokensSoldAtIco = 0;
uint256 public minimumTokenThreshold;
bool public etherHasBeenReturnedToInvestors = false;
uint256 public softCap;
uint256 public runTimeAfterSoftCapReached;
uint256 public dateSoftCapWasReached = 0;
uint256 public maxFundsThatCanBeWithdrawnByOwners = 0;
uint256 public fundsWithdrawnByOwners = 0;
uint8 immediateAllowancePercentage;
uint8 firstYearAllowancePercentage;
uint8 secondYearAllowancePercentage;
mapping (uint8 => uint8) public weekBonuses; // Bonus of 20% is stored as 120, 10% as 110 etc.
modifier onlyWhenIcoParametersAreSet {
require(icoParametersSet);
_;
}
modifier onlyWhenIcoParametersAreNotSet {
require(!icoParametersSet);
_;
}
modifier onlyDuringIco {
require(icoParametersSet);
updateContract();
require(isIcoRunning());
_;
}
/*** End ICO Variables ***/
/*** Begin ICO Setters ***/
function setIcoParametersSet(bool set) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoParametersSet = set;
}
function setIcoBeginDate(uint256 beginDate) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoBeginDate = beginDate;
}
function setIcoEndDate (uint256 endDate) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoEndDate = endDate;
}
function setSoftCap (uint256 cap) onlyWhenIcoParametersAreNotSet onlyOwners public {
softCap = cap;
}
function setRunTimeAfterSoftCapReached (uint256 runTime) onlyWhenIcoParametersAreNotSet onlyOwners public {
runTimeAfterSoftCapReached = runTime;
}
function setImmediateAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
immediateAllowancePercentage = allowancePercentage;
}
function setFirstYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
firstYearAllowancePercentage = allowancePercentage;
}
function setSecondYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
secondYearAllowancePercentage = allowancePercentage;
}
function initialiseToken() public {
require(!tokenInitialised);
name = "BaraToken";
symbol = "BRT";
totalSupply = 160000000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
currentSeller = msg.sender;
owners[msg.sender] = true;
owners[0x1434e028b12D196AcBE5304A94d0a5F816eb5d55] = true;
tokenInitialised = true;
}
function() payable public {
buyTokens();
}
function updateContract() onlyWhenIcoParametersAreSet public {
if (hasSoftCapBeenReached() && dateSoftCapWasReached == 0) {
dateSoftCapWasReached = now;
bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached > icoEndDate);
if (!reachingSoftCapWillExtendIco)
icoEndDate = dateSoftCapWasReached + runTimeAfterSoftCapReached;
}
if (!isBeforeIco())
updateOwnersWithdrawAllowance();
}
function isBeforeIco() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (now <= icoBeginDate);
}
function isIcoRunning() onlyWhenIcoParametersAreSet internal view returns (bool) {
bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached) > icoEndDate;
bool afterBeginDate = now > icoBeginDate;
bool beforeEndDate = now < icoEndDate;
if (hasSoftCapBeenReached() && !reachingSoftCapWillExtendIco)
beforeEndDate = now < (dateSoftCapWasReached + runTimeAfterSoftCapReached);
bool running = afterBeginDate && beforeEndDate;
return running;
}
function isAfterIco() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (now > icoEndDate);
}
function hasSoftCapBeenReached() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (tokensSoldAtIco >= softCap && softCap != 0);
}
// In the first week of the ICO, there will be a bonus, say 20%, then the second week 10%,
// of tokens. This retrieves that bonus. 20% is stored as 120, 10% as 110, etc.
function getWeekBonus(uint256 amountPurchased) onlyWhenIcoParametersAreSet internal view returns (uint256) {
uint256 weekBonus = uint256(weekBonuses[getWeeksPassedSinceStartOfIco()]);
if (weekBonus != 0)
return (amountPurchased * weekBonus) / 100;
return amountPurchased;
}
function getTimeSinceEndOfIco() onlyWhenIcoParametersAreSet internal view returns (uint256) {
require(now > icoEndDate);
uint256 timeSinceEndOfIco = now - icoEndDate;
return timeSinceEndOfIco;
}
function getWeeksPassedSinceStartOfIco() onlyWhenIcoParametersAreSet internal view returns (uint8) {
require(!isBeforeIco());
uint256 timeSinceIco = now - icoBeginDate;
uint8 weeksPassedSinceIco = uint8(timeSinceIco / weekLength);
return weeksPassedSinceIco;
}
// Update how much the owners can withdraw based on how much time has passed
// since the end of the ICO
function updateOwnersWithdrawAllowance() onlyWhenIcoParametersAreSet internal {
if (isAfterIco()) {
uint256 totalFunds = this.balance;
maxFundsThatCanBeWithdrawnByOwners = 0;
uint256 immediateAllowance = (totalFunds * immediateAllowancePercentage) / 100;
bool secondYear = now - icoEndDate >= yearLength;
uint8 monthsPassedSinceIco = getMonthsPassedEndOfSinceIco();
if (secondYear) {
uint256 monthsPassedInSecondYear = monthsPassedSinceIco - 12;
// (monthsPassed / 12) * (allowancePercentage / 100) i.e. (monthsPassed * allowancePercentage / 1200)
// all multiplied by the totalFunds available to be withdrwan
// They're multiplied in one line to ensure not losing any information since we don't have floats
// The minimum a person can buy is 1/10^12 tokens and we have 18 decimals, meaning always at least
// 6 decimals to hold information done in multiplication/division
uint256 secondYearAllowance = ((totalFunds * secondYearAllowancePercentage * monthsPassedInSecondYear) / 1200);
}
uint8 monthsPassedInFirstYear = monthsPassedSinceIco;
if (secondYear)
monthsPassedInFirstYear = 12;
uint256 firstYearAllowance = ((totalFunds * firstYearAllowancePercentage * monthsPassedInFirstYear) / 1200);
maxFundsThatCanBeWithdrawnByOwners = immediateAllowance + firstYearAllowance + secondYearAllowance;
}
}
function getMonthsPassedEndOfSinceIco() onlyWhenIcoParametersAreSet internal view returns (uint8) {
uint256 timePassedSinceIco = now - icoEndDate;
uint8 monthsPassedSinceIco = uint8(timePassedSinceIco / weekLength);
return monthsPassedSinceIco + 1;
}
// Check if the amount the owners are attempting to withdraw is within their current allowance
function amountIsWithinOwnersAllowance(uint256 amountToWithdraw) internal view returns (bool) {
if (now - icoEndDate >= yearLength * 2)
return true;
uint256 totalFundsWithdrawnAfterThisTransaction = fundsWithdrawnByOwners + amountToWithdraw;
bool withinAllowance = totalFundsWithdrawnAfterThisTransaction <= maxFundsThatCanBeWithdrawnByOwners;
return withinAllowance;
}
function buyTokens() onlyDuringIco payable public {
require(allowBuying);
require(!frozenAccounts[msg.sender]);
require(msg.value > 0);
uint256 numberOfTokensPurchased = msg.value / sellPrice;
require(numberOfTokensPurchased >= 10 ** 6);
numberOfTokensPurchased = getWeekBonus(numberOfTokensPurchased);
_transfer(currentSeller, msg.sender, numberOfTokensPurchased);
tokensSoldAtIco += numberOfTokensPurchased;
if (!(etherSpent[msg.sender] > 0)) {
investors[investorCount] = msg.sender;
investorCount++;
}
etherSpent[msg.sender] += msg.value;
}
/* These generate a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event FrozenFunds(address target, bool frozen);
event NewSellPrice(uint256 _sellPrice);
function setTokenName(string tokenName) onlyOwners public {
name = tokenName;
}
function setTokenSymbol(string tokenSymbol) onlyOwners public {
symbol = tokenSymbol;
}
function setAllowTransfers(bool allow) onlyOwners public {
allowTransfers = allow;
}
function setAllowBurns(bool allow) onlyOwners public {
allowBurns = allow;
}
function setAllowBuying(bool allow) onlyOwners public {
allowBuying = allow;
}
function setSellPrice(uint256 _sellPrice) onlyOwners public {
sellPrice = _sellPrice;
NewSellPrice(_sellPrice);
}
function setCurrentSeller(address newSeller) onlyOwners public {
currentSeller = newSeller;
}
function ownersTransfer(address _to, uint256 _amount) onlyOwners public {
_transfer(msg.sender, _to, _amount);
}
function transfer(address _to, uint256 _value) public {
require(allowTransfers && !isOwner(msg.sender));
_transfer(msg.sender, _to, _value);
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccounts[_from]);
require(!frozenAccounts[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwners public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function burn(uint256 amount) public {
require(allowBurns && !isOwner(msg.sender));
require(balanceOf[msg.sender] >= amount);
balanceOf[msg.sender] -= amount;
totalSupply -= amount;
Burn(msg.sender, amount);
}
function burnFrom(address from, uint256 amount) onlyOwners public {
require (balanceOf[from] >= amount);
balanceOf[from] -= amount;
totalSupply -= amount;
Burn(from, amount);
}
function freezeAccount(address target, bool freeze) onlyOwners public {
frozenAccounts[target] = freeze;
FrozenFunds(target, freeze);
}
function addOwner(address owner) onlyOwners public {
owners[owner] = true;
}
function removeOwner(address owner) onlyOwners public {
owners[owner] = false;
}
function sendContractFundsToAddress(uint256 amount, address recipient) onlyOwners public {
require(icoParametersSet);
require(isAfterIco());
require(tokensSoldAtIco >= minimumTokenThreshold);
require(amount <= this.balance);
updateContract();
require(amountIsWithinOwnersAllowance(amount));
recipient.transfer(amount);
}
function returnEtherToInvestors() onlyOwners onlyWhenIcoParametersAreSet public {
require(isAfterIco());
require(!etherHasBeenReturnedToInvestors);
require(tokensSoldAtIco < minimumTokenThreshold);
for (uint64 investorNumber; investorNumber < investorCount; investorNumber++) {
address investor = investors[investorNumber];
uint256 amountToSend = etherSpent[investor];
investor.transfer(amountToSend);
}
etherHasBeenReturnedToInvestors = true;
}
function getContractBalance() public view returns (uint256) {
return this.balance;
}
} | getWeekBonus | function getWeekBonus(uint256 amountPurchased) onlyWhenIcoParametersAreSet internal view returns (uint256) {
uint256 weekBonus = uint256(weekBonuses[getWeeksPassedSinceStartOfIco()]);
if (weekBonus != 0)
return (amountPurchased * weekBonus) / 100;
return amountPurchased;
}
| // In the first week of the ICO, there will be a bonus, say 20%, then the second week 10%,
// of tokens. This retrieves that bonus. 20% is stored as 120, 10% as 110, etc. | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8626e638e1b9f4aafcab7372e5ea55969e0b4cce15dfd389fd021a12efa1b2ad | {
"func_code_index": [
6892,
7193
]
} | 7,414 |
|||
TokenERC20 | TokenERC20.sol | 0xd70e66775a74a9aedeac6e28313e1033cd726552 | Solidity | TokenERC20 | contract TokenERC20 {
/* Begin Owned Contract Members */
// An array of owners
mapping (address => bool) public owners;
// Has the next action been authorised by another owner
bool public nextActionIsAuthorised = false;
address public actionAuthorisedBy;
// Does an owner-only action have to be authorised by another owner
bool public requireAuthorisation = true;
function isOwner(address addressToCheck) view public returns (bool) {
return owners[addressToCheck];
}
modifier onlyOwners {
require(isOwner(msg.sender));
if (requireAuthorisation) {
checkActionIsAuthorisedAndReset();
}
_;
}
function authoriseNextAction() public {
require(isOwner(msg.sender));
require(requireAuthorisation);
require(!nextActionIsAuthorised);
nextActionIsAuthorised = true;
actionAuthorisedBy = msg.sender;
}
function checkActionIsAuthorisedAndReset() public {
require(isOwner(msg.sender));
bool isValidAuthorisationRequest = (nextActionIsAuthorised && actionAuthorisedBy != msg.sender);
require(isValidAuthorisationRequest);
nextActionIsAuthorised = false;
}
function setRequireAuthorisation(bool _requireAuthorisation) onlyOwners public {
requireAuthorisation = _requireAuthorisation;
}
/* End Owned Contract Members */
// Public variables of the token
bool public tokenInitialised = false;
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
uint256 public sellPrice;
address public currentSeller;
// Are users currently allowed to...
bool public allowTransfers = false; // transfer their tokens
bool public allowBurns = false; // burn their tokens
bool public allowBuying = false; // buy tokens
// This creates an array with...
mapping (address => uint256) public balanceOf; // all balances
mapping (address => uint256) public etherSpent; // how much an addeess has spent
mapping (address => bool) public frozenAccounts; // frozen accounts
address[] investors;
uint64 public investorCount;
/*** Begin ICO Variables ***/
// Unit lenghts for week, month and year
uint256 constant public weekLength = 60 * 60 * 24 * 7;
uint256 constant public monthLength = 2627856; // (60 * 60 * 24 * 30.415) As to not have to re-adjust for different month lengths
uint256 constant public yearLength = 60 * 60 * 24 * 7 * 52;
uint256 public icoBeginDate;
uint256 public icoEndDate;
bool public icoParametersSet = false;
uint256 public tokensSoldAtIco = 0;
uint256 public minimumTokenThreshold;
bool public etherHasBeenReturnedToInvestors = false;
uint256 public softCap;
uint256 public runTimeAfterSoftCapReached;
uint256 public dateSoftCapWasReached = 0;
uint256 public maxFundsThatCanBeWithdrawnByOwners = 0;
uint256 public fundsWithdrawnByOwners = 0;
uint8 immediateAllowancePercentage;
uint8 firstYearAllowancePercentage;
uint8 secondYearAllowancePercentage;
mapping (uint8 => uint8) public weekBonuses; // Bonus of 20% is stored as 120, 10% as 110 etc.
modifier onlyWhenIcoParametersAreSet {
require(icoParametersSet);
_;
}
modifier onlyWhenIcoParametersAreNotSet {
require(!icoParametersSet);
_;
}
modifier onlyDuringIco {
require(icoParametersSet);
updateContract();
require(isIcoRunning());
_;
}
/*** End ICO Variables ***/
/*** Begin ICO Setters ***/
function setIcoParametersSet(bool set) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoParametersSet = set;
}
function setIcoBeginDate(uint256 beginDate) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoBeginDate = beginDate;
}
function setIcoEndDate (uint256 endDate) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoEndDate = endDate;
}
function setSoftCap (uint256 cap) onlyWhenIcoParametersAreNotSet onlyOwners public {
softCap = cap;
}
function setRunTimeAfterSoftCapReached (uint256 runTime) onlyWhenIcoParametersAreNotSet onlyOwners public {
runTimeAfterSoftCapReached = runTime;
}
function setImmediateAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
immediateAllowancePercentage = allowancePercentage;
}
function setFirstYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
firstYearAllowancePercentage = allowancePercentage;
}
function setSecondYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
secondYearAllowancePercentage = allowancePercentage;
}
function initialiseToken() public {
require(!tokenInitialised);
name = "BaraToken";
symbol = "BRT";
totalSupply = 160000000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
currentSeller = msg.sender;
owners[msg.sender] = true;
owners[0x1434e028b12D196AcBE5304A94d0a5F816eb5d55] = true;
tokenInitialised = true;
}
function() payable public {
buyTokens();
}
function updateContract() onlyWhenIcoParametersAreSet public {
if (hasSoftCapBeenReached() && dateSoftCapWasReached == 0) {
dateSoftCapWasReached = now;
bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached > icoEndDate);
if (!reachingSoftCapWillExtendIco)
icoEndDate = dateSoftCapWasReached + runTimeAfterSoftCapReached;
}
if (!isBeforeIco())
updateOwnersWithdrawAllowance();
}
function isBeforeIco() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (now <= icoBeginDate);
}
function isIcoRunning() onlyWhenIcoParametersAreSet internal view returns (bool) {
bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached) > icoEndDate;
bool afterBeginDate = now > icoBeginDate;
bool beforeEndDate = now < icoEndDate;
if (hasSoftCapBeenReached() && !reachingSoftCapWillExtendIco)
beforeEndDate = now < (dateSoftCapWasReached + runTimeAfterSoftCapReached);
bool running = afterBeginDate && beforeEndDate;
return running;
}
function isAfterIco() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (now > icoEndDate);
}
function hasSoftCapBeenReached() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (tokensSoldAtIco >= softCap && softCap != 0);
}
// In the first week of the ICO, there will be a bonus, say 20%, then the second week 10%,
// of tokens. This retrieves that bonus. 20% is stored as 120, 10% as 110, etc.
function getWeekBonus(uint256 amountPurchased) onlyWhenIcoParametersAreSet internal view returns (uint256) {
uint256 weekBonus = uint256(weekBonuses[getWeeksPassedSinceStartOfIco()]);
if (weekBonus != 0)
return (amountPurchased * weekBonus) / 100;
return amountPurchased;
}
function getTimeSinceEndOfIco() onlyWhenIcoParametersAreSet internal view returns (uint256) {
require(now > icoEndDate);
uint256 timeSinceEndOfIco = now - icoEndDate;
return timeSinceEndOfIco;
}
function getWeeksPassedSinceStartOfIco() onlyWhenIcoParametersAreSet internal view returns (uint8) {
require(!isBeforeIco());
uint256 timeSinceIco = now - icoBeginDate;
uint8 weeksPassedSinceIco = uint8(timeSinceIco / weekLength);
return weeksPassedSinceIco;
}
// Update how much the owners can withdraw based on how much time has passed
// since the end of the ICO
function updateOwnersWithdrawAllowance() onlyWhenIcoParametersAreSet internal {
if (isAfterIco()) {
uint256 totalFunds = this.balance;
maxFundsThatCanBeWithdrawnByOwners = 0;
uint256 immediateAllowance = (totalFunds * immediateAllowancePercentage) / 100;
bool secondYear = now - icoEndDate >= yearLength;
uint8 monthsPassedSinceIco = getMonthsPassedEndOfSinceIco();
if (secondYear) {
uint256 monthsPassedInSecondYear = monthsPassedSinceIco - 12;
// (monthsPassed / 12) * (allowancePercentage / 100) i.e. (monthsPassed * allowancePercentage / 1200)
// all multiplied by the totalFunds available to be withdrwan
// They're multiplied in one line to ensure not losing any information since we don't have floats
// The minimum a person can buy is 1/10^12 tokens and we have 18 decimals, meaning always at least
// 6 decimals to hold information done in multiplication/division
uint256 secondYearAllowance = ((totalFunds * secondYearAllowancePercentage * monthsPassedInSecondYear) / 1200);
}
uint8 monthsPassedInFirstYear = monthsPassedSinceIco;
if (secondYear)
monthsPassedInFirstYear = 12;
uint256 firstYearAllowance = ((totalFunds * firstYearAllowancePercentage * monthsPassedInFirstYear) / 1200);
maxFundsThatCanBeWithdrawnByOwners = immediateAllowance + firstYearAllowance + secondYearAllowance;
}
}
function getMonthsPassedEndOfSinceIco() onlyWhenIcoParametersAreSet internal view returns (uint8) {
uint256 timePassedSinceIco = now - icoEndDate;
uint8 monthsPassedSinceIco = uint8(timePassedSinceIco / weekLength);
return monthsPassedSinceIco + 1;
}
// Check if the amount the owners are attempting to withdraw is within their current allowance
function amountIsWithinOwnersAllowance(uint256 amountToWithdraw) internal view returns (bool) {
if (now - icoEndDate >= yearLength * 2)
return true;
uint256 totalFundsWithdrawnAfterThisTransaction = fundsWithdrawnByOwners + amountToWithdraw;
bool withinAllowance = totalFundsWithdrawnAfterThisTransaction <= maxFundsThatCanBeWithdrawnByOwners;
return withinAllowance;
}
function buyTokens() onlyDuringIco payable public {
require(allowBuying);
require(!frozenAccounts[msg.sender]);
require(msg.value > 0);
uint256 numberOfTokensPurchased = msg.value / sellPrice;
require(numberOfTokensPurchased >= 10 ** 6);
numberOfTokensPurchased = getWeekBonus(numberOfTokensPurchased);
_transfer(currentSeller, msg.sender, numberOfTokensPurchased);
tokensSoldAtIco += numberOfTokensPurchased;
if (!(etherSpent[msg.sender] > 0)) {
investors[investorCount] = msg.sender;
investorCount++;
}
etherSpent[msg.sender] += msg.value;
}
/* These generate a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event FrozenFunds(address target, bool frozen);
event NewSellPrice(uint256 _sellPrice);
function setTokenName(string tokenName) onlyOwners public {
name = tokenName;
}
function setTokenSymbol(string tokenSymbol) onlyOwners public {
symbol = tokenSymbol;
}
function setAllowTransfers(bool allow) onlyOwners public {
allowTransfers = allow;
}
function setAllowBurns(bool allow) onlyOwners public {
allowBurns = allow;
}
function setAllowBuying(bool allow) onlyOwners public {
allowBuying = allow;
}
function setSellPrice(uint256 _sellPrice) onlyOwners public {
sellPrice = _sellPrice;
NewSellPrice(_sellPrice);
}
function setCurrentSeller(address newSeller) onlyOwners public {
currentSeller = newSeller;
}
function ownersTransfer(address _to, uint256 _amount) onlyOwners public {
_transfer(msg.sender, _to, _amount);
}
function transfer(address _to, uint256 _value) public {
require(allowTransfers && !isOwner(msg.sender));
_transfer(msg.sender, _to, _value);
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccounts[_from]);
require(!frozenAccounts[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwners public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function burn(uint256 amount) public {
require(allowBurns && !isOwner(msg.sender));
require(balanceOf[msg.sender] >= amount);
balanceOf[msg.sender] -= amount;
totalSupply -= amount;
Burn(msg.sender, amount);
}
function burnFrom(address from, uint256 amount) onlyOwners public {
require (balanceOf[from] >= amount);
balanceOf[from] -= amount;
totalSupply -= amount;
Burn(from, amount);
}
function freezeAccount(address target, bool freeze) onlyOwners public {
frozenAccounts[target] = freeze;
FrozenFunds(target, freeze);
}
function addOwner(address owner) onlyOwners public {
owners[owner] = true;
}
function removeOwner(address owner) onlyOwners public {
owners[owner] = false;
}
function sendContractFundsToAddress(uint256 amount, address recipient) onlyOwners public {
require(icoParametersSet);
require(isAfterIco());
require(tokensSoldAtIco >= minimumTokenThreshold);
require(amount <= this.balance);
updateContract();
require(amountIsWithinOwnersAllowance(amount));
recipient.transfer(amount);
}
function returnEtherToInvestors() onlyOwners onlyWhenIcoParametersAreSet public {
require(isAfterIco());
require(!etherHasBeenReturnedToInvestors);
require(tokensSoldAtIco < minimumTokenThreshold);
for (uint64 investorNumber; investorNumber < investorCount; investorNumber++) {
address investor = investors[investorNumber];
uint256 amountToSend = etherSpent[investor];
investor.transfer(amountToSend);
}
etherHasBeenReturnedToInvestors = true;
}
function getContractBalance() public view returns (uint256) {
return this.balance;
}
} | updateOwnersWithdrawAllowance | function updateOwnersWithdrawAllowance() onlyWhenIcoParametersAreSet internal {
if (isAfterIco()) {
uint256 totalFunds = this.balance;
maxFundsThatCanBeWithdrawnByOwners = 0;
uint256 immediateAllowance = (totalFunds * immediateAllowancePercentage) / 100;
bool secondYear = now - icoEndDate >= yearLength;
uint8 monthsPassedSinceIco = getMonthsPassedEndOfSinceIco();
if (secondYear) {
uint256 monthsPassedInSecondYear = monthsPassedSinceIco - 12;
// (monthsPassed / 12) * (allowancePercentage / 100) i.e. (monthsPassed * allowancePercentage / 1200)
// all multiplied by the totalFunds available to be withdrwan
// They're multiplied in one line to ensure not losing any information since we don't have floats
// The minimum a person can buy is 1/10^12 tokens and we have 18 decimals, meaning always at least
// 6 decimals to hold information done in multiplication/division
uint256 secondYearAllowance = ((totalFunds * secondYearAllowancePercentage * monthsPassedInSecondYear) / 1200);
}
uint8 monthsPassedInFirstYear = monthsPassedSinceIco;
if (secondYear)
monthsPassedInFirstYear = 12;
uint256 firstYearAllowance = ((totalFunds * firstYearAllowancePercentage * monthsPassedInFirstYear) / 1200);
maxFundsThatCanBeWithdrawnByOwners = immediateAllowance + firstYearAllowance + secondYearAllowance;
}
}
| // Update how much the owners can withdraw based on how much time has passed
// since the end of the ICO | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8626e638e1b9f4aafcab7372e5ea55969e0b4cce15dfd389fd021a12efa1b2ad | {
"func_code_index": [
7826,
9290
]
} | 7,415 |
|||
TokenERC20 | TokenERC20.sol | 0xd70e66775a74a9aedeac6e28313e1033cd726552 | Solidity | TokenERC20 | contract TokenERC20 {
/* Begin Owned Contract Members */
// An array of owners
mapping (address => bool) public owners;
// Has the next action been authorised by another owner
bool public nextActionIsAuthorised = false;
address public actionAuthorisedBy;
// Does an owner-only action have to be authorised by another owner
bool public requireAuthorisation = true;
function isOwner(address addressToCheck) view public returns (bool) {
return owners[addressToCheck];
}
modifier onlyOwners {
require(isOwner(msg.sender));
if (requireAuthorisation) {
checkActionIsAuthorisedAndReset();
}
_;
}
function authoriseNextAction() public {
require(isOwner(msg.sender));
require(requireAuthorisation);
require(!nextActionIsAuthorised);
nextActionIsAuthorised = true;
actionAuthorisedBy = msg.sender;
}
function checkActionIsAuthorisedAndReset() public {
require(isOwner(msg.sender));
bool isValidAuthorisationRequest = (nextActionIsAuthorised && actionAuthorisedBy != msg.sender);
require(isValidAuthorisationRequest);
nextActionIsAuthorised = false;
}
function setRequireAuthorisation(bool _requireAuthorisation) onlyOwners public {
requireAuthorisation = _requireAuthorisation;
}
/* End Owned Contract Members */
// Public variables of the token
bool public tokenInitialised = false;
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
uint256 public sellPrice;
address public currentSeller;
// Are users currently allowed to...
bool public allowTransfers = false; // transfer their tokens
bool public allowBurns = false; // burn their tokens
bool public allowBuying = false; // buy tokens
// This creates an array with...
mapping (address => uint256) public balanceOf; // all balances
mapping (address => uint256) public etherSpent; // how much an addeess has spent
mapping (address => bool) public frozenAccounts; // frozen accounts
address[] investors;
uint64 public investorCount;
/*** Begin ICO Variables ***/
// Unit lenghts for week, month and year
uint256 constant public weekLength = 60 * 60 * 24 * 7;
uint256 constant public monthLength = 2627856; // (60 * 60 * 24 * 30.415) As to not have to re-adjust for different month lengths
uint256 constant public yearLength = 60 * 60 * 24 * 7 * 52;
uint256 public icoBeginDate;
uint256 public icoEndDate;
bool public icoParametersSet = false;
uint256 public tokensSoldAtIco = 0;
uint256 public minimumTokenThreshold;
bool public etherHasBeenReturnedToInvestors = false;
uint256 public softCap;
uint256 public runTimeAfterSoftCapReached;
uint256 public dateSoftCapWasReached = 0;
uint256 public maxFundsThatCanBeWithdrawnByOwners = 0;
uint256 public fundsWithdrawnByOwners = 0;
uint8 immediateAllowancePercentage;
uint8 firstYearAllowancePercentage;
uint8 secondYearAllowancePercentage;
mapping (uint8 => uint8) public weekBonuses; // Bonus of 20% is stored as 120, 10% as 110 etc.
modifier onlyWhenIcoParametersAreSet {
require(icoParametersSet);
_;
}
modifier onlyWhenIcoParametersAreNotSet {
require(!icoParametersSet);
_;
}
modifier onlyDuringIco {
require(icoParametersSet);
updateContract();
require(isIcoRunning());
_;
}
/*** End ICO Variables ***/
/*** Begin ICO Setters ***/
function setIcoParametersSet(bool set) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoParametersSet = set;
}
function setIcoBeginDate(uint256 beginDate) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoBeginDate = beginDate;
}
function setIcoEndDate (uint256 endDate) onlyWhenIcoParametersAreNotSet onlyOwners public {
icoEndDate = endDate;
}
function setSoftCap (uint256 cap) onlyWhenIcoParametersAreNotSet onlyOwners public {
softCap = cap;
}
function setRunTimeAfterSoftCapReached (uint256 runTime) onlyWhenIcoParametersAreNotSet onlyOwners public {
runTimeAfterSoftCapReached = runTime;
}
function setImmediateAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
immediateAllowancePercentage = allowancePercentage;
}
function setFirstYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
firstYearAllowancePercentage = allowancePercentage;
}
function setSecondYearAllowancePercentage(uint8 allowancePercentage) onlyWhenIcoParametersAreNotSet onlyOwners public {
secondYearAllowancePercentage = allowancePercentage;
}
function initialiseToken() public {
require(!tokenInitialised);
name = "BaraToken";
symbol = "BRT";
totalSupply = 160000000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
currentSeller = msg.sender;
owners[msg.sender] = true;
owners[0x1434e028b12D196AcBE5304A94d0a5F816eb5d55] = true;
tokenInitialised = true;
}
function() payable public {
buyTokens();
}
function updateContract() onlyWhenIcoParametersAreSet public {
if (hasSoftCapBeenReached() && dateSoftCapWasReached == 0) {
dateSoftCapWasReached = now;
bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached > icoEndDate);
if (!reachingSoftCapWillExtendIco)
icoEndDate = dateSoftCapWasReached + runTimeAfterSoftCapReached;
}
if (!isBeforeIco())
updateOwnersWithdrawAllowance();
}
function isBeforeIco() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (now <= icoBeginDate);
}
function isIcoRunning() onlyWhenIcoParametersAreSet internal view returns (bool) {
bool reachingSoftCapWillExtendIco = (dateSoftCapWasReached + runTimeAfterSoftCapReached) > icoEndDate;
bool afterBeginDate = now > icoBeginDate;
bool beforeEndDate = now < icoEndDate;
if (hasSoftCapBeenReached() && !reachingSoftCapWillExtendIco)
beforeEndDate = now < (dateSoftCapWasReached + runTimeAfterSoftCapReached);
bool running = afterBeginDate && beforeEndDate;
return running;
}
function isAfterIco() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (now > icoEndDate);
}
function hasSoftCapBeenReached() onlyWhenIcoParametersAreSet internal view returns (bool) {
return (tokensSoldAtIco >= softCap && softCap != 0);
}
// In the first week of the ICO, there will be a bonus, say 20%, then the second week 10%,
// of tokens. This retrieves that bonus. 20% is stored as 120, 10% as 110, etc.
function getWeekBonus(uint256 amountPurchased) onlyWhenIcoParametersAreSet internal view returns (uint256) {
uint256 weekBonus = uint256(weekBonuses[getWeeksPassedSinceStartOfIco()]);
if (weekBonus != 0)
return (amountPurchased * weekBonus) / 100;
return amountPurchased;
}
function getTimeSinceEndOfIco() onlyWhenIcoParametersAreSet internal view returns (uint256) {
require(now > icoEndDate);
uint256 timeSinceEndOfIco = now - icoEndDate;
return timeSinceEndOfIco;
}
function getWeeksPassedSinceStartOfIco() onlyWhenIcoParametersAreSet internal view returns (uint8) {
require(!isBeforeIco());
uint256 timeSinceIco = now - icoBeginDate;
uint8 weeksPassedSinceIco = uint8(timeSinceIco / weekLength);
return weeksPassedSinceIco;
}
// Update how much the owners can withdraw based on how much time has passed
// since the end of the ICO
function updateOwnersWithdrawAllowance() onlyWhenIcoParametersAreSet internal {
if (isAfterIco()) {
uint256 totalFunds = this.balance;
maxFundsThatCanBeWithdrawnByOwners = 0;
uint256 immediateAllowance = (totalFunds * immediateAllowancePercentage) / 100;
bool secondYear = now - icoEndDate >= yearLength;
uint8 monthsPassedSinceIco = getMonthsPassedEndOfSinceIco();
if (secondYear) {
uint256 monthsPassedInSecondYear = monthsPassedSinceIco - 12;
// (monthsPassed / 12) * (allowancePercentage / 100) i.e. (monthsPassed * allowancePercentage / 1200)
// all multiplied by the totalFunds available to be withdrwan
// They're multiplied in one line to ensure not losing any information since we don't have floats
// The minimum a person can buy is 1/10^12 tokens and we have 18 decimals, meaning always at least
// 6 decimals to hold information done in multiplication/division
uint256 secondYearAllowance = ((totalFunds * secondYearAllowancePercentage * monthsPassedInSecondYear) / 1200);
}
uint8 monthsPassedInFirstYear = monthsPassedSinceIco;
if (secondYear)
monthsPassedInFirstYear = 12;
uint256 firstYearAllowance = ((totalFunds * firstYearAllowancePercentage * monthsPassedInFirstYear) / 1200);
maxFundsThatCanBeWithdrawnByOwners = immediateAllowance + firstYearAllowance + secondYearAllowance;
}
}
function getMonthsPassedEndOfSinceIco() onlyWhenIcoParametersAreSet internal view returns (uint8) {
uint256 timePassedSinceIco = now - icoEndDate;
uint8 monthsPassedSinceIco = uint8(timePassedSinceIco / weekLength);
return monthsPassedSinceIco + 1;
}
// Check if the amount the owners are attempting to withdraw is within their current allowance
function amountIsWithinOwnersAllowance(uint256 amountToWithdraw) internal view returns (bool) {
if (now - icoEndDate >= yearLength * 2)
return true;
uint256 totalFundsWithdrawnAfterThisTransaction = fundsWithdrawnByOwners + amountToWithdraw;
bool withinAllowance = totalFundsWithdrawnAfterThisTransaction <= maxFundsThatCanBeWithdrawnByOwners;
return withinAllowance;
}
function buyTokens() onlyDuringIco payable public {
require(allowBuying);
require(!frozenAccounts[msg.sender]);
require(msg.value > 0);
uint256 numberOfTokensPurchased = msg.value / sellPrice;
require(numberOfTokensPurchased >= 10 ** 6);
numberOfTokensPurchased = getWeekBonus(numberOfTokensPurchased);
_transfer(currentSeller, msg.sender, numberOfTokensPurchased);
tokensSoldAtIco += numberOfTokensPurchased;
if (!(etherSpent[msg.sender] > 0)) {
investors[investorCount] = msg.sender;
investorCount++;
}
etherSpent[msg.sender] += msg.value;
}
/* These generate a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event FrozenFunds(address target, bool frozen);
event NewSellPrice(uint256 _sellPrice);
function setTokenName(string tokenName) onlyOwners public {
name = tokenName;
}
function setTokenSymbol(string tokenSymbol) onlyOwners public {
symbol = tokenSymbol;
}
function setAllowTransfers(bool allow) onlyOwners public {
allowTransfers = allow;
}
function setAllowBurns(bool allow) onlyOwners public {
allowBurns = allow;
}
function setAllowBuying(bool allow) onlyOwners public {
allowBuying = allow;
}
function setSellPrice(uint256 _sellPrice) onlyOwners public {
sellPrice = _sellPrice;
NewSellPrice(_sellPrice);
}
function setCurrentSeller(address newSeller) onlyOwners public {
currentSeller = newSeller;
}
function ownersTransfer(address _to, uint256 _amount) onlyOwners public {
_transfer(msg.sender, _to, _amount);
}
function transfer(address _to, uint256 _value) public {
require(allowTransfers && !isOwner(msg.sender));
_transfer(msg.sender, _to, _value);
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccounts[_from]);
require(!frozenAccounts[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwners public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function burn(uint256 amount) public {
require(allowBurns && !isOwner(msg.sender));
require(balanceOf[msg.sender] >= amount);
balanceOf[msg.sender] -= amount;
totalSupply -= amount;
Burn(msg.sender, amount);
}
function burnFrom(address from, uint256 amount) onlyOwners public {
require (balanceOf[from] >= amount);
balanceOf[from] -= amount;
totalSupply -= amount;
Burn(from, amount);
}
function freezeAccount(address target, bool freeze) onlyOwners public {
frozenAccounts[target] = freeze;
FrozenFunds(target, freeze);
}
function addOwner(address owner) onlyOwners public {
owners[owner] = true;
}
function removeOwner(address owner) onlyOwners public {
owners[owner] = false;
}
function sendContractFundsToAddress(uint256 amount, address recipient) onlyOwners public {
require(icoParametersSet);
require(isAfterIco());
require(tokensSoldAtIco >= minimumTokenThreshold);
require(amount <= this.balance);
updateContract();
require(amountIsWithinOwnersAllowance(amount));
recipient.transfer(amount);
}
function returnEtherToInvestors() onlyOwners onlyWhenIcoParametersAreSet public {
require(isAfterIco());
require(!etherHasBeenReturnedToInvestors);
require(tokensSoldAtIco < minimumTokenThreshold);
for (uint64 investorNumber; investorNumber < investorCount; investorNumber++) {
address investor = investors[investorNumber];
uint256 amountToSend = etherSpent[investor];
investor.transfer(amountToSend);
}
etherHasBeenReturnedToInvestors = true;
}
function getContractBalance() public view returns (uint256) {
return this.balance;
}
} | amountIsWithinOwnersAllowance | function amountIsWithinOwnersAllowance(uint256 amountToWithdraw) internal view returns (bool) {
if (now - icoEndDate >= yearLength * 2)
return true;
uint256 totalFundsWithdrawnAfterThisTransaction = fundsWithdrawnByOwners + amountToWithdraw;
bool withinAllowance = totalFundsWithdrawnAfterThisTransaction <= maxFundsThatCanBeWithdrawnByOwners;
return withinAllowance;
}
| // Check if the amount the owners are attempting to withdraw is within their current allowance | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8626e638e1b9f4aafcab7372e5ea55969e0b4cce15dfd389fd021a12efa1b2ad | {
"func_code_index": [
9673,
10075
]
} | 7,416 |
|||
SNXRewardUniLPStrategy | contracts/hardworkInterface/IVault.sol | 0x987a168e19f6f64d6ab08ae0e0fe77ea3d79baac | Solidity | IVault | interface IVault {
// the IERC20 part is the share
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256);
// hard work should be callable only by the controller (by the hard worker) or by governance
function doHardWork() external;
function rebalance() external;
} | underlyingBalanceInVault | function underlyingBalanceInVault() external view returns (uint256);
| // the IERC20 part is the share | LineComment | v0.5.16+commit.9c3226ce | MIT | bzzr://b9974e4880b432f849903fea2a6432e29f2677ef70cc6b4e3aa5460dff20cbbf | {
"func_code_index": [
59,
132
]
} | 7,417 |
||
SNXRewardUniLPStrategy | contracts/hardworkInterface/IVault.sol | 0x987a168e19f6f64d6ab08ae0e0fe77ea3d79baac | Solidity | IVault | interface IVault {
// the IERC20 part is the share
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder) view external returns (uint256);
// hard work should be callable only by the controller (by the hard worker) or by governance
function doHardWork() external;
function rebalance() external;
} | doHardWork | function doHardWork() external;
| // hard work should be callable only by the controller (by the hard worker) or by governance | LineComment | v0.5.16+commit.9c3226ce | MIT | bzzr://b9974e4880b432f849903fea2a6432e29f2677ef70cc6b4e3aa5460dff20cbbf | {
"func_code_index": [
1096,
1132
]
} | 7,418 |
||
TimeLock | @c-layer/governance/contracts/lock/TimeLock.sol | 0x99332f76fa35524ae3ce6657a86f588e8819c3d1 | Solidity | TimeLock | contract TimeLock is Ownable {
address payable public target;
uint64 public lockedUntil;
modifier whenUnlocked() {
require(lockedUntil < currentTime(), "TL01");
_;
}
constructor(address payable _target, uint64 _lockedUntil) public {
require(_target != address(0), "TL02");
require(_lockedUntil > currentTime(), "TL03");
lockedUntil = _lockedUntil;
target = _target;
}
receive() external payable {
require(callInternal(), "TL04");
}
fallback() external payable {
require(callInternal(), "TL04");
}
function callInternal() internal onlyOwner whenUnlocked returns (bool) {
(bool success, ) =
// solhint-disable-next-line avoid-call-value, avoid-low-level-calls
target.call{value: msg.value}(msg.data);
return success;
}
/**
* @dev current time
*/
function currentTime() internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return now;
}
} | /**
* @title TimeLock
* @dev Time locked contract
*
* Error messages
* TL01: Contract is locked
* TL02: Target must be defined
* TL03: Cannot be locked in the past
* TL04: Execution must be successfull
*/ | NatSpecMultiLine | currentTime | function currentTime() internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return now;
}
| /**
* @dev current time
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://f38c1955786aaa4dc0abe92ae7623ffaba309330bba42781d973986b5f9fb98c | {
"func_code_index": [
866,
998
]
} | 7,419 |
FindTheCureCoin | FindTheCureCoin.sol | 0xea5b80723a90539e32e38011af39b0821822dc2f | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | totalSupply | function totalSupply() constant returns (uint256 supply) {}
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://0615cb161426828d1ff3596b40750e8da8f6698f6bf853a7fcd5c9b85928b2e5 | {
"func_code_index": [
60,
124
]
} | 7,420 |
|||
FindTheCureCoin | FindTheCureCoin.sol | 0xea5b80723a90539e32e38011af39b0821822dc2f | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance) {}
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://0615cb161426828d1ff3596b40750e8da8f6698f6bf853a7fcd5c9b85928b2e5 | {
"func_code_index": [
232,
309
]
} | 7,421 |
|||
FindTheCureCoin | FindTheCureCoin.sol | 0xea5b80723a90539e32e38011af39b0821822dc2f | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://0615cb161426828d1ff3596b40750e8da8f6698f6bf853a7fcd5c9b85928b2e5 | {
"func_code_index": [
546,
623
]
} | 7,422 |
|||
FindTheCureCoin | FindTheCureCoin.sol | 0xea5b80723a90539e32e38011af39b0821822dc2f | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://0615cb161426828d1ff3596b40750e8da8f6698f6bf853a7fcd5c9b85928b2e5 | {
"func_code_index": [
946,
1042
]
} | 7,423 |
|||
FindTheCureCoin | FindTheCureCoin.sol | 0xea5b80723a90539e32e38011af39b0821822dc2f | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) returns (bool success) {}
| /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://0615cb161426828d1ff3596b40750e8da8f6698f6bf853a7fcd5c9b85928b2e5 | {
"func_code_index": [
1326,
1407
]
} | 7,424 |
|||
FindTheCureCoin | FindTheCureCoin.sol | 0xea5b80723a90539e32e38011af39b0821822dc2f | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
| /// @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 | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://0615cb161426828d1ff3596b40750e8da8f6698f6bf853a7fcd5c9b85928b2e5 | {
"func_code_index": [
1615,
1712
]
} | 7,425 |
|||
FindTheCureCoin | FindTheCureCoin.sol | 0xea5b80723a90539e32e38011af39b0821822dc2f | Solidity | FindTheCureCoin | contract FindTheCureCoin is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; // Token Name
uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18
string public symbol; // An identifier: eg SBX, XPR etc..
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH?
uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here.
address public fundsWallet; // Where should the raised ETH go?
// This is a constructor function
// which means the following function name has to match the contract name declared above
function FindTheCureCoin() {
balances[msg.sender] = 5000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)
totalSupply = 5000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "FindTheCureCoin"; // Set the name for display purposes (CHANGE THIS)
decimals = 1; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "FtCC"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 9000; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | FindTheCureCoin | function FindTheCureCoin() {
balances[msg.sender] = 5000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)
totalSupply = 5000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "FindTheCureCoin"; // Set the name for display purposes (CHANGE THIS)
decimals = 1; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "FtCC"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 9000; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
}
| // Where should the raised ETH go?
// This is a constructor function
// which means the following function name has to match the contract name declared above | LineComment | v0.4.24+commit.e67f0147 | bzzr://0615cb161426828d1ff3596b40750e8da8f6698f6bf853a7fcd5c9b85928b2e5 | {
"func_code_index": [
1203,
2207
]
} | 7,426 |
|||
FindTheCureCoin | FindTheCureCoin.sol | 0xea5b80723a90539e32e38011af39b0821822dc2f | Solidity | FindTheCureCoin | contract FindTheCureCoin is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; // Token Name
uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18
string public symbol; // An identifier: eg SBX, XPR etc..
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH?
uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here.
address public fundsWallet; // Where should the raised ETH go?
// This is a constructor function
// which means the following function name has to match the contract name declared above
function FindTheCureCoin() {
balances[msg.sender] = 5000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)
totalSupply = 5000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "FindTheCureCoin"; // Set the name for display purposes (CHANGE THIS)
decimals = 1; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "FtCC"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 9000; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
| /* Approves and then calls the receiving contract */ | Comment | v0.4.24+commit.e67f0147 | bzzr://0615cb161426828d1ff3596b40750e8da8f6698f6bf853a7fcd5c9b85928b2e5 | {
"func_code_index": [
2803,
3608
]
} | 7,427 |
|||
lockEtherPay | lockEtherPay.sol | 0x9ae840651db575b2d7c09a8851a53c22403fae86 | Solidity | lockEtherPay | contract lockEtherPay {
using SafeMath
for uint256;
event NewRound(
uint _timestamp,
uint _round,
uint _initialPot
);
event Bid(
uint _timestamp,
address _address,
uint _amount,
uint _newPot
);
event NewLeader(
uint _timestamp,
address _address,
uint _newPot,
uint _newDeadline
);
event Winner(
uint _timestamp,
address _address,
uint _earnings,
uint _hasntStarted
);
event EarningsWithdrawal(
uint _timestamp,
address _address,
uint _amount
);
event DividendsWithdrawal(
uint _timestamp,
address _address,
uint _dividendShares,
uint _amount,
uint _newTotalDividendShares,
uint _newDividendFund
);
// Initial countdown duration
uint public constant BASE_DURATION = 1 days;
// Amount by which the countdown duration decreases per ether in the pot
uint public constant DURATION_DECREASE_PER_ETHER = 2 minutes;
// Minimum countdown duration
uint public constant MINIMUM_DURATION = 30 minutes;
// Minimum fraction of the pot required by a bidder to become the new leader
uint public constant MIN_LEADER_FRAC_TOP = 1;
uint public constant MIN_LEADER_FRAC_BOT = 100000;
// Fraction of each bid put into the dividend fund
uint public constant DIVIDEND_FUND_FRAC_TOP = 45;
uint public constant DIVIDEND_FUND_FRAC_BOT = 100;
uint public constant FRAC_TOP = 15;
uint public constant FRAC_BOT = 100;
// Mapping from addresses to amounts earned
address _null;
mapping(address => uint) public earnings;
// Mapping from addresses to dividend shares
mapping(address => uint) public dividendShares;
// Total number of keys
uint public totalDividendShares;
address owner;
// Value of the Key fund
uint public dividendFund;
// Current round number
uint public round;
// Current value of the pot
uint public pot;
// Address of the current leader
address public leader;
// Time at which the current round expires
uint public hasntStarted;
function lockEtherPay() public payable {
require(msg.value > 0);
round = 1;
pot = msg.value;
_null = msg.sender;
leader = _null;
totalDividendShares = 300000;
dividendShares[_null] = 300000;
hasntStarted = computeDeadline();
NewRound(now, round, pot);
NewLeader(now, leader, pot, hasntStarted);
owner = msg.sender;
}
function computeDeadline() internal view returns(uint) {
uint _durationDecrease = DURATION_DECREASE_PER_ETHER.mul(pot.div(1 ether));
uint _duration;
if (MINIMUM_DURATION.add(_durationDecrease) > BASE_DURATION) {
_duration = MINIMUM_DURATION;
} else {
_duration = BASE_DURATION.sub(_durationDecrease);
}
return now.add(_duration);
}
modifier blabla {
if (now > hasntStarted) {
uint _nextPot = 0;
uint _leaderEarnings = pot.sub(_nextPot);
Winner(now, leader, _leaderEarnings, hasntStarted);
earnings[leader] = earnings[leader].add(_leaderEarnings);
round++;
pot = _nextPot;
leader = owner;
hasntStarted = computeDeadline();
NewRound(now, round, pot);
NewLeader(now, leader, pot, hasntStarted);
}
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Buy keys
function bid() public payable blabla {
uint _minLeaderAmount = pot.mul(MIN_LEADER_FRAC_TOP).div(MIN_LEADER_FRAC_BOT);
uint _bidAmountToCommunity = msg.value.mul(FRAC_TOP).div(FRAC_BOT);
uint _bidAmountToDividendFund = msg.value.mul(DIVIDEND_FUND_FRAC_TOP).div(DIVIDEND_FUND_FRAC_BOT);
uint _bidAmountToPot = msg.value.sub(_bidAmountToCommunity).sub(_bidAmountToDividendFund);
earnings[_null] = earnings[_null].add(_bidAmountToCommunity);
dividendFund = dividendFund.add(_bidAmountToDividendFund);
pot = pot.add(_bidAmountToPot);
Bid(now, msg.sender, msg.value, pot);
if (msg.value >= _minLeaderAmount) {
uint _dividendShares = msg.value.div(_minLeaderAmount);
dividendShares[msg.sender] = dividendShares[msg.sender].add(_dividendShares);
totalDividendShares = totalDividendShares.add(_dividendShares);
leader = msg.sender;
hasntStarted = computeDeadline();
NewLeader(now, leader, pot, hasntStarted);
}
}
// Withdraw winned pot
function withdrawEarnings() public blabla { require(earnings[msg.sender] > 0);
assert(earnings[msg.sender] <= this.balance);
uint _amount = earnings[msg.sender];
earnings[msg.sender] = 0;
msg.sender.transfer(_amount);
EarningsWithdrawal(now, msg.sender, _amount);
}
// Sell keys
function withdrawDividends() public { require(dividendShares[msg.sender] > 0);
uint _dividendShares = dividendShares[msg.sender];
assert(_dividendShares <= totalDividendShares);
uint _amount = dividendFund.mul(_dividendShares).div(totalDividendShares);
assert(_amount <= this.balance);
dividendShares[msg.sender] = 0;
totalDividendShares = totalDividendShares.sub(_dividendShares);
dividendFund = dividendFund.sub(_amount);
msg.sender.transfer(_amount);
DividendsWithdrawal(now, msg.sender, _dividendShares, _amount, totalDividendShares, dividendFund);
}
// Start
// Not needed in the first round
function start() public onlyOwner { hasntStarted = 0;
}
} | bid | function bid() public payable blabla {
uint _minLeaderAmount = pot.mul(MIN_LEADER_FRAC_TOP).div(MIN_LEADER_FRAC_BOT);
uint _bidAmountToCommunity = msg.value.mul(FRAC_TOP).div(FRAC_BOT);
uint _bidAmountToDividendFund = msg.value.mul(DIVIDEND_FUND_FRAC_TOP).div(DIVIDEND_FUND_FRAC_BOT);
uint _bidAmountToPot = msg.value.sub(_bidAmountToCommunity).sub(_bidAmountToDividendFund);
earnings[_null] = earnings[_null].add(_bidAmountToCommunity);
dividendFund = dividendFund.add(_bidAmountToDividendFund);
pot = pot.add(_bidAmountToPot);
Bid(now, msg.sender, msg.value, pot);
if (msg.value >= _minLeaderAmount) {
uint _dividendShares = msg.value.div(_minLeaderAmount);
dividendShares[msg.sender] = dividendShares[msg.sender].add(_dividendShares);
totalDividendShares = totalDividendShares.add(_dividendShares);
leader = msg.sender;
hasntStarted = computeDeadline();
NewLeader(now, leader, pot, hasntStarted);
}
}
| // Buy keys | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://0c424931ec30eaf12b6b842d051df2f458a08b933cf8269a16a5eeaa3ef7d4d9 | {
"func_code_index": [
3805,
4890
]
} | 7,428 |
|||
lockEtherPay | lockEtherPay.sol | 0x9ae840651db575b2d7c09a8851a53c22403fae86 | Solidity | lockEtherPay | contract lockEtherPay {
using SafeMath
for uint256;
event NewRound(
uint _timestamp,
uint _round,
uint _initialPot
);
event Bid(
uint _timestamp,
address _address,
uint _amount,
uint _newPot
);
event NewLeader(
uint _timestamp,
address _address,
uint _newPot,
uint _newDeadline
);
event Winner(
uint _timestamp,
address _address,
uint _earnings,
uint _hasntStarted
);
event EarningsWithdrawal(
uint _timestamp,
address _address,
uint _amount
);
event DividendsWithdrawal(
uint _timestamp,
address _address,
uint _dividendShares,
uint _amount,
uint _newTotalDividendShares,
uint _newDividendFund
);
// Initial countdown duration
uint public constant BASE_DURATION = 1 days;
// Amount by which the countdown duration decreases per ether in the pot
uint public constant DURATION_DECREASE_PER_ETHER = 2 minutes;
// Minimum countdown duration
uint public constant MINIMUM_DURATION = 30 minutes;
// Minimum fraction of the pot required by a bidder to become the new leader
uint public constant MIN_LEADER_FRAC_TOP = 1;
uint public constant MIN_LEADER_FRAC_BOT = 100000;
// Fraction of each bid put into the dividend fund
uint public constant DIVIDEND_FUND_FRAC_TOP = 45;
uint public constant DIVIDEND_FUND_FRAC_BOT = 100;
uint public constant FRAC_TOP = 15;
uint public constant FRAC_BOT = 100;
// Mapping from addresses to amounts earned
address _null;
mapping(address => uint) public earnings;
// Mapping from addresses to dividend shares
mapping(address => uint) public dividendShares;
// Total number of keys
uint public totalDividendShares;
address owner;
// Value of the Key fund
uint public dividendFund;
// Current round number
uint public round;
// Current value of the pot
uint public pot;
// Address of the current leader
address public leader;
// Time at which the current round expires
uint public hasntStarted;
function lockEtherPay() public payable {
require(msg.value > 0);
round = 1;
pot = msg.value;
_null = msg.sender;
leader = _null;
totalDividendShares = 300000;
dividendShares[_null] = 300000;
hasntStarted = computeDeadline();
NewRound(now, round, pot);
NewLeader(now, leader, pot, hasntStarted);
owner = msg.sender;
}
function computeDeadline() internal view returns(uint) {
uint _durationDecrease = DURATION_DECREASE_PER_ETHER.mul(pot.div(1 ether));
uint _duration;
if (MINIMUM_DURATION.add(_durationDecrease) > BASE_DURATION) {
_duration = MINIMUM_DURATION;
} else {
_duration = BASE_DURATION.sub(_durationDecrease);
}
return now.add(_duration);
}
modifier blabla {
if (now > hasntStarted) {
uint _nextPot = 0;
uint _leaderEarnings = pot.sub(_nextPot);
Winner(now, leader, _leaderEarnings, hasntStarted);
earnings[leader] = earnings[leader].add(_leaderEarnings);
round++;
pot = _nextPot;
leader = owner;
hasntStarted = computeDeadline();
NewRound(now, round, pot);
NewLeader(now, leader, pot, hasntStarted);
}
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Buy keys
function bid() public payable blabla {
uint _minLeaderAmount = pot.mul(MIN_LEADER_FRAC_TOP).div(MIN_LEADER_FRAC_BOT);
uint _bidAmountToCommunity = msg.value.mul(FRAC_TOP).div(FRAC_BOT);
uint _bidAmountToDividendFund = msg.value.mul(DIVIDEND_FUND_FRAC_TOP).div(DIVIDEND_FUND_FRAC_BOT);
uint _bidAmountToPot = msg.value.sub(_bidAmountToCommunity).sub(_bidAmountToDividendFund);
earnings[_null] = earnings[_null].add(_bidAmountToCommunity);
dividendFund = dividendFund.add(_bidAmountToDividendFund);
pot = pot.add(_bidAmountToPot);
Bid(now, msg.sender, msg.value, pot);
if (msg.value >= _minLeaderAmount) {
uint _dividendShares = msg.value.div(_minLeaderAmount);
dividendShares[msg.sender] = dividendShares[msg.sender].add(_dividendShares);
totalDividendShares = totalDividendShares.add(_dividendShares);
leader = msg.sender;
hasntStarted = computeDeadline();
NewLeader(now, leader, pot, hasntStarted);
}
}
// Withdraw winned pot
function withdrawEarnings() public blabla { require(earnings[msg.sender] > 0);
assert(earnings[msg.sender] <= this.balance);
uint _amount = earnings[msg.sender];
earnings[msg.sender] = 0;
msg.sender.transfer(_amount);
EarningsWithdrawal(now, msg.sender, _amount);
}
// Sell keys
function withdrawDividends() public { require(dividendShares[msg.sender] > 0);
uint _dividendShares = dividendShares[msg.sender];
assert(_dividendShares <= totalDividendShares);
uint _amount = dividendFund.mul(_dividendShares).div(totalDividendShares);
assert(_amount <= this.balance);
dividendShares[msg.sender] = 0;
totalDividendShares = totalDividendShares.sub(_dividendShares);
dividendFund = dividendFund.sub(_amount);
msg.sender.transfer(_amount);
DividendsWithdrawal(now, msg.sender, _dividendShares, _amount, totalDividendShares, dividendFund);
}
// Start
// Not needed in the first round
function start() public onlyOwner { hasntStarted = 0;
}
} | withdrawEarnings | function withdrawEarnings() public blabla { require(earnings[msg.sender] > 0);
assert(earnings[msg.sender] <= this.balance);
uint _amount = earnings[msg.sender];
earnings[msg.sender] = 0;
msg.sender.transfer(_amount);
EarningsWithdrawal(now, msg.sender, _amount);
}
| // Withdraw winned pot | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://0c424931ec30eaf12b6b842d051df2f458a08b933cf8269a16a5eeaa3ef7d4d9 | {
"func_code_index": [
4925,
5245
]
} | 7,429 |
|||
lockEtherPay | lockEtherPay.sol | 0x9ae840651db575b2d7c09a8851a53c22403fae86 | Solidity | lockEtherPay | contract lockEtherPay {
using SafeMath
for uint256;
event NewRound(
uint _timestamp,
uint _round,
uint _initialPot
);
event Bid(
uint _timestamp,
address _address,
uint _amount,
uint _newPot
);
event NewLeader(
uint _timestamp,
address _address,
uint _newPot,
uint _newDeadline
);
event Winner(
uint _timestamp,
address _address,
uint _earnings,
uint _hasntStarted
);
event EarningsWithdrawal(
uint _timestamp,
address _address,
uint _amount
);
event DividendsWithdrawal(
uint _timestamp,
address _address,
uint _dividendShares,
uint _amount,
uint _newTotalDividendShares,
uint _newDividendFund
);
// Initial countdown duration
uint public constant BASE_DURATION = 1 days;
// Amount by which the countdown duration decreases per ether in the pot
uint public constant DURATION_DECREASE_PER_ETHER = 2 minutes;
// Minimum countdown duration
uint public constant MINIMUM_DURATION = 30 minutes;
// Minimum fraction of the pot required by a bidder to become the new leader
uint public constant MIN_LEADER_FRAC_TOP = 1;
uint public constant MIN_LEADER_FRAC_BOT = 100000;
// Fraction of each bid put into the dividend fund
uint public constant DIVIDEND_FUND_FRAC_TOP = 45;
uint public constant DIVIDEND_FUND_FRAC_BOT = 100;
uint public constant FRAC_TOP = 15;
uint public constant FRAC_BOT = 100;
// Mapping from addresses to amounts earned
address _null;
mapping(address => uint) public earnings;
// Mapping from addresses to dividend shares
mapping(address => uint) public dividendShares;
// Total number of keys
uint public totalDividendShares;
address owner;
// Value of the Key fund
uint public dividendFund;
// Current round number
uint public round;
// Current value of the pot
uint public pot;
// Address of the current leader
address public leader;
// Time at which the current round expires
uint public hasntStarted;
function lockEtherPay() public payable {
require(msg.value > 0);
round = 1;
pot = msg.value;
_null = msg.sender;
leader = _null;
totalDividendShares = 300000;
dividendShares[_null] = 300000;
hasntStarted = computeDeadline();
NewRound(now, round, pot);
NewLeader(now, leader, pot, hasntStarted);
owner = msg.sender;
}
function computeDeadline() internal view returns(uint) {
uint _durationDecrease = DURATION_DECREASE_PER_ETHER.mul(pot.div(1 ether));
uint _duration;
if (MINIMUM_DURATION.add(_durationDecrease) > BASE_DURATION) {
_duration = MINIMUM_DURATION;
} else {
_duration = BASE_DURATION.sub(_durationDecrease);
}
return now.add(_duration);
}
modifier blabla {
if (now > hasntStarted) {
uint _nextPot = 0;
uint _leaderEarnings = pot.sub(_nextPot);
Winner(now, leader, _leaderEarnings, hasntStarted);
earnings[leader] = earnings[leader].add(_leaderEarnings);
round++;
pot = _nextPot;
leader = owner;
hasntStarted = computeDeadline();
NewRound(now, round, pot);
NewLeader(now, leader, pot, hasntStarted);
}
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Buy keys
function bid() public payable blabla {
uint _minLeaderAmount = pot.mul(MIN_LEADER_FRAC_TOP).div(MIN_LEADER_FRAC_BOT);
uint _bidAmountToCommunity = msg.value.mul(FRAC_TOP).div(FRAC_BOT);
uint _bidAmountToDividendFund = msg.value.mul(DIVIDEND_FUND_FRAC_TOP).div(DIVIDEND_FUND_FRAC_BOT);
uint _bidAmountToPot = msg.value.sub(_bidAmountToCommunity).sub(_bidAmountToDividendFund);
earnings[_null] = earnings[_null].add(_bidAmountToCommunity);
dividendFund = dividendFund.add(_bidAmountToDividendFund);
pot = pot.add(_bidAmountToPot);
Bid(now, msg.sender, msg.value, pot);
if (msg.value >= _minLeaderAmount) {
uint _dividendShares = msg.value.div(_minLeaderAmount);
dividendShares[msg.sender] = dividendShares[msg.sender].add(_dividendShares);
totalDividendShares = totalDividendShares.add(_dividendShares);
leader = msg.sender;
hasntStarted = computeDeadline();
NewLeader(now, leader, pot, hasntStarted);
}
}
// Withdraw winned pot
function withdrawEarnings() public blabla { require(earnings[msg.sender] > 0);
assert(earnings[msg.sender] <= this.balance);
uint _amount = earnings[msg.sender];
earnings[msg.sender] = 0;
msg.sender.transfer(_amount);
EarningsWithdrawal(now, msg.sender, _amount);
}
// Sell keys
function withdrawDividends() public { require(dividendShares[msg.sender] > 0);
uint _dividendShares = dividendShares[msg.sender];
assert(_dividendShares <= totalDividendShares);
uint _amount = dividendFund.mul(_dividendShares).div(totalDividendShares);
assert(_amount <= this.balance);
dividendShares[msg.sender] = 0;
totalDividendShares = totalDividendShares.sub(_dividendShares);
dividendFund = dividendFund.sub(_amount);
msg.sender.transfer(_amount);
DividendsWithdrawal(now, msg.sender, _dividendShares, _amount, totalDividendShares, dividendFund);
}
// Start
// Not needed in the first round
function start() public onlyOwner { hasntStarted = 0;
}
} | withdrawDividends | function withdrawDividends() public { require(dividendShares[msg.sender] > 0);
uint _dividendShares = dividendShares[msg.sender];
assert(_dividendShares <= totalDividendShares);
uint _amount = dividendFund.mul(_dividendShares).div(totalDividendShares);
assert(_amount <= this.balance);
dividendShares[msg.sender] = 0;
totalDividendShares = totalDividendShares.sub(_dividendShares);
dividendFund = dividendFund.sub(_amount);
msg.sender.transfer(_amount);
DividendsWithdrawal(now, msg.sender, _dividendShares, _amount, totalDividendShares, dividendFund);
}
| // Sell keys | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://0c424931ec30eaf12b6b842d051df2f458a08b933cf8269a16a5eeaa3ef7d4d9 | {
"func_code_index": [
5271,
5916
]
} | 7,430 |
|||
lockEtherPay | lockEtherPay.sol | 0x9ae840651db575b2d7c09a8851a53c22403fae86 | Solidity | lockEtherPay | contract lockEtherPay {
using SafeMath
for uint256;
event NewRound(
uint _timestamp,
uint _round,
uint _initialPot
);
event Bid(
uint _timestamp,
address _address,
uint _amount,
uint _newPot
);
event NewLeader(
uint _timestamp,
address _address,
uint _newPot,
uint _newDeadline
);
event Winner(
uint _timestamp,
address _address,
uint _earnings,
uint _hasntStarted
);
event EarningsWithdrawal(
uint _timestamp,
address _address,
uint _amount
);
event DividendsWithdrawal(
uint _timestamp,
address _address,
uint _dividendShares,
uint _amount,
uint _newTotalDividendShares,
uint _newDividendFund
);
// Initial countdown duration
uint public constant BASE_DURATION = 1 days;
// Amount by which the countdown duration decreases per ether in the pot
uint public constant DURATION_DECREASE_PER_ETHER = 2 minutes;
// Minimum countdown duration
uint public constant MINIMUM_DURATION = 30 minutes;
// Minimum fraction of the pot required by a bidder to become the new leader
uint public constant MIN_LEADER_FRAC_TOP = 1;
uint public constant MIN_LEADER_FRAC_BOT = 100000;
// Fraction of each bid put into the dividend fund
uint public constant DIVIDEND_FUND_FRAC_TOP = 45;
uint public constant DIVIDEND_FUND_FRAC_BOT = 100;
uint public constant FRAC_TOP = 15;
uint public constant FRAC_BOT = 100;
// Mapping from addresses to amounts earned
address _null;
mapping(address => uint) public earnings;
// Mapping from addresses to dividend shares
mapping(address => uint) public dividendShares;
// Total number of keys
uint public totalDividendShares;
address owner;
// Value of the Key fund
uint public dividendFund;
// Current round number
uint public round;
// Current value of the pot
uint public pot;
// Address of the current leader
address public leader;
// Time at which the current round expires
uint public hasntStarted;
function lockEtherPay() public payable {
require(msg.value > 0);
round = 1;
pot = msg.value;
_null = msg.sender;
leader = _null;
totalDividendShares = 300000;
dividendShares[_null] = 300000;
hasntStarted = computeDeadline();
NewRound(now, round, pot);
NewLeader(now, leader, pot, hasntStarted);
owner = msg.sender;
}
function computeDeadline() internal view returns(uint) {
uint _durationDecrease = DURATION_DECREASE_PER_ETHER.mul(pot.div(1 ether));
uint _duration;
if (MINIMUM_DURATION.add(_durationDecrease) > BASE_DURATION) {
_duration = MINIMUM_DURATION;
} else {
_duration = BASE_DURATION.sub(_durationDecrease);
}
return now.add(_duration);
}
modifier blabla {
if (now > hasntStarted) {
uint _nextPot = 0;
uint _leaderEarnings = pot.sub(_nextPot);
Winner(now, leader, _leaderEarnings, hasntStarted);
earnings[leader] = earnings[leader].add(_leaderEarnings);
round++;
pot = _nextPot;
leader = owner;
hasntStarted = computeDeadline();
NewRound(now, round, pot);
NewLeader(now, leader, pot, hasntStarted);
}
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Buy keys
function bid() public payable blabla {
uint _minLeaderAmount = pot.mul(MIN_LEADER_FRAC_TOP).div(MIN_LEADER_FRAC_BOT);
uint _bidAmountToCommunity = msg.value.mul(FRAC_TOP).div(FRAC_BOT);
uint _bidAmountToDividendFund = msg.value.mul(DIVIDEND_FUND_FRAC_TOP).div(DIVIDEND_FUND_FRAC_BOT);
uint _bidAmountToPot = msg.value.sub(_bidAmountToCommunity).sub(_bidAmountToDividendFund);
earnings[_null] = earnings[_null].add(_bidAmountToCommunity);
dividendFund = dividendFund.add(_bidAmountToDividendFund);
pot = pot.add(_bidAmountToPot);
Bid(now, msg.sender, msg.value, pot);
if (msg.value >= _minLeaderAmount) {
uint _dividendShares = msg.value.div(_minLeaderAmount);
dividendShares[msg.sender] = dividendShares[msg.sender].add(_dividendShares);
totalDividendShares = totalDividendShares.add(_dividendShares);
leader = msg.sender;
hasntStarted = computeDeadline();
NewLeader(now, leader, pot, hasntStarted);
}
}
// Withdraw winned pot
function withdrawEarnings() public blabla { require(earnings[msg.sender] > 0);
assert(earnings[msg.sender] <= this.balance);
uint _amount = earnings[msg.sender];
earnings[msg.sender] = 0;
msg.sender.transfer(_amount);
EarningsWithdrawal(now, msg.sender, _amount);
}
// Sell keys
function withdrawDividends() public { require(dividendShares[msg.sender] > 0);
uint _dividendShares = dividendShares[msg.sender];
assert(_dividendShares <= totalDividendShares);
uint _amount = dividendFund.mul(_dividendShares).div(totalDividendShares);
assert(_amount <= this.balance);
dividendShares[msg.sender] = 0;
totalDividendShares = totalDividendShares.sub(_dividendShares);
dividendFund = dividendFund.sub(_amount);
msg.sender.transfer(_amount);
DividendsWithdrawal(now, msg.sender, _dividendShares, _amount, totalDividendShares, dividendFund);
}
// Start
// Not needed in the first round
function start() public onlyOwner { hasntStarted = 0;
}
} | start | function start() public onlyOwner { hasntStarted = 0;
}
| // Start
// Not needed in the first round | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://0c424931ec30eaf12b6b842d051df2f458a08b933cf8269a16a5eeaa3ef7d4d9 | {
"func_code_index": [
5971,
6036
]
} | 7,431 |
|||
lockEtherPay | lockEtherPay.sol | 0x9ae840651db575b2d7c09a8851a53c22403fae86 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | mul | 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 Multiplies two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://0c424931ec30eaf12b6b842d051df2f458a08b933cf8269a16a5eeaa3ef7d4d9 | {
"func_code_index": [
95,
307
]
} | 7,432 |
|
lockEtherPay | lockEtherPay.sol | 0x9ae840651db575b2d7c09a8851a53c22403fae86 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | div | 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 Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://0c424931ec30eaf12b6b842d051df2f458a08b933cf8269a16a5eeaa3ef7d4d9 | {
"func_code_index": [
399,
691
]
} | 7,433 |
|
lockEtherPay | lockEtherPay.sol | 0x9ae840651db575b2d7c09a8851a53c22403fae86 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
| /**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://0c424931ec30eaf12b6b842d051df2f458a08b933cf8269a16a5eeaa3ef7d4d9 | {
"func_code_index": [
814,
941
]
} | 7,434 |
|
lockEtherPay | lockEtherPay.sol | 0x9ae840651db575b2d7c09a8851a53c22403fae86 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://0c424931ec30eaf12b6b842d051df2f458a08b933cf8269a16a5eeaa3ef7d4d9 | {
"func_code_index": [
1013,
1164
]
} | 7,435 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | setStartTime | function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
| // @dev Function setting the start time of the system | LineComment | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
4769,
4932
]
} | 7,436 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | buy | function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
| /// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
5049,
5230
]
} | 7,437 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | buyFor | function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
| /// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
5349,
5564
]
} | 7,438 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
| /**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
5740,
5871
]
} | 7,439 |
||
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | reinvest | function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
| /// @dev Converts all of caller's dividends to tokens. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
5934,
6673
]
} | 7,440 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | exit | function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
| /// @dev Alias of sell() and withdraw(). | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
6722,
7016
]
} | 7,441 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | withdraw | function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
| /// @dev Withdraws all of the callers earnings. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
7072,
7702
]
} | 7,442 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | sell | function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
| /// @dev Liquifies tokens to ethereum. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
7749,
9028
]
} | 7,443 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | transfer | function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
| /**
* @dev Transfer tokens from the caller to a new holder.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
9113,
10151
]
} | 7,444 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | totalEthereumBalance | function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
| /**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
10424,
10538
]
} | 7,445 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
| /// @dev Retrieve the total token supply. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
10588,
10684
]
} | 7,446 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | myTokens | function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
| /// @dev Retrieve the tokens owned by the caller. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
10742,
10898
]
} | 7,447 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | myDividends | function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
| /**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
11257,
11538
]
} | 7,448 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
| /// @dev Retrieve the token balance of any single address. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
11605,
11748
]
} | 7,449 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | dividendsOf | function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
| /// @dev Retrieve the dividend balance of any single address. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
11818,
12047
]
} | 7,450 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | sellPrice | function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
| /// @dev Return the sell price of 1 individual token. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
12109,
12641
]
} | 7,451 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | buyPrice | function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
| /// @dev Return the buy price of 1 individual token. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
12702,
13233
]
} | 7,452 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | calculateTokensReceived | function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
| /// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
13333,
13708
]
} | 7,453 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | calculateEthereumReceived | function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
| /// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
13809,
14210
]
} | 7,454 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | calculateUntaxedEthereumReceived | function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
| /// @dev Function for the frontend to get untaxed receivable ethereum. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
14289,
14696
]
} | 7,455 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | exitFee | function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
| /// @dev Function for getting the current exitFee | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
14756,
15340
]
} | 7,456 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | isPremine | function isPremine() public view returns (bool) {
return depositCount_<=7;
}
| // @dev Function for find if premine | LineComment | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
15385,
15478
]
} | 7,457 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | isStarted | function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
| // @dev Function for find if premine | LineComment | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
15523,
15631
]
} | 7,458 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | purchaseTokens | function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
| /// @dev Internal function to actually purchase the tokens. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
15851,
19232
]
} | 7,459 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | ethereumToTokens_ | function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
| /**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
19530,
20483
]
} | 7,460 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | tokensToEthereum_ | function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
| /**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
20747,
21462
]
} | 7,461 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | HyperEX | contract HyperEX {
/*=================================
= MODIFIERS =
=================================*/
/// @dev Only people with tokens
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
/// @dev Only people with profits
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
/// @dev notGasbag
modifier notGasbag() {
require(tx.gasprice < 200999999999);
_;
}
/// @dev Preventing unstable dumping and limit ambassador mine
modifier antiEarlyWhale {
if (address(this).balance -msg.value < whaleBalanceLimit){
require(msg.value <= maxEarlyStake);
}
if (depositCount_ == 0){
require(ambassadors_[msg.sender] && msg.value == 0.25 ether);
}else
if (depositCount_ < 6){
require(ambassadors_[msg.sender] && msg.value == 0.75 ether);
}else
if (depositCount_ == 6 || depositCount_==7){
require(ambassadors_[msg.sender] && msg.value == 1 ether);
}
_;
}
/// @dev notGasbag
modifier isControlled() {
require(isPremine() || isStarted());
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "HYPER Token";
string public symbol = "HYPER";
uint8 constant public decimals = 18;
/// @dev 10% dividends for token purchase
uint8 constant internal entryFee_ = 10;
/// @dev 50% dividends for token selling
uint8 constant internal startExitFee_ = 50;
/// @dev 15% dividends for token selling after step
uint8 constant internal finalExitFee_ = 15;
/// @dev Exit fee falls over period of 30 days
uint256 constant internal exitFeeFallDuration_ = 30 days;
/// @dev 3% masternode
uint8 constant internal refferalFee_ = 3;
/// @dev P3D pricing
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
/// @dev 300 needed for masternode activation
uint256 public stakingRequirement = 300e18;
/// @dev anti-early-whale
uint256 public maxEarlyStake = 2.5 ether;
uint256 public whaleBalanceLimit = 75 ether;
/// @dev apex starting gun
address public apex;
/// @dev starting
uint256 public startTime = 0; // January 1, 1970 12:00:00
/*=================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => uint256) internal bonusBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
uint256 public depositCount_;
mapping(address => bool) internal ambassadors_;
/*=======================================
= CONSTRUCTOR =
=======================================*/
constructor () public {
//HyperETH Funding Allocations
ambassadors_[msg.sender]=true;
//1
ambassadors_[0xee6854929ce78fb7c5453e63ee2ff76f780677a9]=true;
//2
ambassadors_[0x7DF0AB219B7e1488F521e9EEE0DDAcf608C90AB9]=true;
apex = msg.sender;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
// @dev Function setting the start time of the system
function setStartTime(uint256 _startTime) public {
require(msg.sender==apex && !isStarted() && now < _startTime);
startTime = _startTime;
}
/// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
function buy(address _referredBy) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , msg.sender);
}
/// @dev Converts to tokens on behalf of the customer - this allows gifting and integration with other systems
function buyFor(address _referredBy, address _customerAddress) antiEarlyWhale notGasbag isControlled public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy , _customerAddress);
}
/**
* @dev Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function() antiEarlyWhale notGasbag isControlled payable public {
purchaseTokens(msg.value, 0x0 , msg.sender);
}
/// @dev Converts all of caller's dividends to tokens.
function reinvest() onlyStronghands public {
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0 , _customerAddress);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/// @dev Alias of sell() and withdraw().
function exit() public {
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
// capitulation
withdraw();
}
/// @dev Withdraws all of the callers earnings.
function withdraw() onlyStronghands public {
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/// @dev Liquifies tokens to ethereum.
function sell(uint256 _amountOfTokens) onlyBagholders public {
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
/**
* @dev Transfer tokens from the caller to a new holder.
*/
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*=====================================
= HELPERS AND CALCULATORS =
=====================================*/
/**
* @dev Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
/// @dev Retrieve the total token supply.
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
/// @dev Retrieve the tokens owned by the caller.
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/// @dev Retrieve the token balance of any single address.
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
/// @dev Retrieve the dividend balance of any single address.
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/// @dev Return the sell price of 1 individual token.
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Return the buy price of 1 individual token.
function buyPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders.
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders.
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/// @dev Function for the frontend to get untaxed receivable ethereum.
function calculateUntaxedEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
//uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100);
//uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _ethereum;
}
/// @dev Function for getting the current exitFee
function exitFee() public view returns (uint8) {
if (startTime==0){
return startExitFee_;
}
if ( now < startTime) {
return 0;
}
uint256 secondsPassed = now - startTime;
if (secondsPassed >= exitFeeFallDuration_) {
return finalExitFee_;
}
uint8 totalChange = startExitFee_ - finalExitFee_;
uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_);
uint8 currentFee = startExitFee_- currentChange;
return currentFee;
}
// @dev Function for find if premine
function isPremine() public view returns (bool) {
return depositCount_<=7;
}
// @dev Function for find if premine
function isStarted() public view returns (bool) {
return startTime!=0 && now > startTime;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/// @dev Internal function to actually purchase the tokens.
function purchaseTokens(uint256 _incomingEthereum, address _referredBy , address _customerAddress) internal returns (uint256) {
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
// is the user referred by a masternode?
if (
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
// really i know you think you do but you don't
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
// Keep track
depositCount_++;
return _amountOfTokens;
}
/**
* @dev Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
) / (tokenPriceIncremental_)
) - (tokenSupply_);
return _tokensReceived;
}
/**
* @dev Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))
) - tokenPriceIncremental_
) * (tokens_ - 1e18)
), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2
)
/ 1e18);
return _etherReceived;
}
/// @dev This is where all your gas goes.
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | /***
* https://hypereth.net
*
* No administrators or developers, this contract is fully autonomous
*
* 10 % entry fee which is allocated to
* 3 % of entry fee to masternode referrals
* 0 % transfer fee
* Exit fee starts at 50% from contract start
* Exit fee decreases over 30 days until 15%
* Stays at 15% forever.
*/ | NatSpecMultiLine | sqrt | function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
| /// @dev This is where all your gas goes. | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
21512,
21726
]
} | 7,462 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | mul | 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 Multiplies two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
95,
308
]
} | 7,463 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | div | 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 Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
398,
691
]
} | 7,464 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| /**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
812,
940
]
} | 7,465 |
|
HyperEX | HyperEX.sol | 0xe4166b945b79675e41f21668db2875b5e0128435 | Solidity | SafeMath | 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://09f278c178195a28bb7b0091ba5eb98cebaa8bc500848c548c189b6179ca3645 | {
"func_code_index": [
1010,
1162
]
} | 7,466 |
|
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
| // | LineComment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
1527,
4642
]
} | 7,467 |
||||
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | claimEthIfFailed | function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
| /* Users can claim ETH by themselves if they want to in case of ETH failure */ | Comment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
4736,
5515
]
} | 7,468 |
|||
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | batchReturnEthIfFailed | function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
| /* Owner can return eth for multiple users in one call */ | Comment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
5583,
6877
]
} | 7,469 |
|||
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | changeMultisigAddress | function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
| /* Owner sets new address of escrow */ | Comment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
6930,
7049
]
} | 7,470 |
|||
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | participantCount | function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
| /* Show how many participants was */ | Comment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
7098,
7201
]
} | 7,471 |
|||
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | claimTeamTokens | function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
| /* Owner can claim reserved tokens on the end of crowsale */ | Comment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
7272,
7592
]
} | 7,472 |
|||
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | setTokenContract | function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
| /* Set token contract where mints will be done (tokens will be issued) */ | Comment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
7682,
7847
]
} | 7,473 |
|||
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | withdrawEther | function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
| /* Withdraw funds from contract */ | Comment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
8603,
9063
]
} | 7,474 |
|||
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | getVlsTokenAddress | function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
| /* Getters */ | Comment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
9519,
9654
]
} | 7,475 |
|||
ValusCrowdsale | ValusCrowdsale.sol | 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad | Solidity | ValusCrowdsale | contract ValusCrowdsale is owned {
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
IValusToken valusTokenContract;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool crowdsaleHasStarted;
bool softCapReached;
bool hardCapReached;
bool crowdsaleHasSucessfulyEnded;
uint256 blocksInADay;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event CrowdsaleStarted(uint256 _blockNumber);
event CrowdsaleSoftCapReached(uint256 _blockNumber);
event CrowdsaleHardCapReached(uint256 _blockNumber);
event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function ValusCrowdsale(){
blocksInADay = 2950;
startBlock = 4363310;
endBlock = startBlock + blocksInADay * 29;
minEthToRaise = 3030 * 10**18;
maxEthToRaise = 30303 * 10**18;
multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2;
}
//
/* User accessible methods */
//
function () payable{
if(msg.value == 0) throw;
if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended
if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction
if (block.number >= startBlock){ // Check if the Crowdsale should start
crowdsaleHasStarted = true; // Set that the Crowdsale has started
CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value; // Add to total eth Raised
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value));
if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event
softCapReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended
CrowdsaleHardCapReached(block.number);
hardCapReached = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure */
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
/* Owner can return eth for multiple users in one call */
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of escrow */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Show how many participants was */
function participantCount() constant returns(uint){
return nextFreeParticipantIndex;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimTeamTokens(address _to) onlyOwner{
if (!crowdsaleHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */
ownerHasClaimedTokens = true;
}
/* Set token contract where mints will be done (tokens will be issued) */
function setTokenContract(address _valusTokenContractAddress) onlyOwner {
valusTokenContract = IValusToken(_valusTokenContractAddress);
}
function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882;
if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667;
if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511;
if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402;
if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300;
}
/* Withdraw funds from contract */
function withdrawEther() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endCrowdsale() onlyOwner{
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
crowdsaleHasSucessfulyEnded = true;
CrowdsaleEndedSuccessfuly(block.number, totalEthRaised);
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
/* Getters */
function getVlsTokenAddress() constant returns(address _tokenAddress){
return address(valusTokenContract);
}
function crowdsaleInProgress() constant returns (bool answer){
return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded;
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
} | withdrawRemainingBalanceForManualRecovery | function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if Crowdsale failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
| /* Withdraw remaining balance to manually return where contract send has failed */ | Comment | v0.4.17+commit.bdeb9e52 | bzzr://5fbc9caad1e9202c37f16ea630d23fd7f93f6e7fc617a760cd008730541cad14 | {
"func_code_index": [
10086,
10668
]
} | 7,476 |
|||
ImpulsevenSwapV2Factory | core/ImpulsevenSwapV2Pair.sol | 0x4f6703952d3139353a7a8212414a104912c79974 | Solidity | ImpulsevenSwapV2Pair | contract ImpulsevenSwapV2Pair is IImpulsevenSwapV2Pair, ImpulsevenSwapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'ImpulsevenSwapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ImpulsevenSwapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'ImpulsevenSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(10).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'ImpulsevenSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'ImpulsevenSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IImpulsevenSwapV2Callee(to).ImpulsevenSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'ImpulsevenSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'ImpulsevenSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | initialize | function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'ImpulsevenSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
| // called once by the factory at time of deployment | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://01b3a29875675e373f6a18d5a80c386b8ea850f96117d278cddd4bc206973931 | {
"func_code_index": [
2112,
2334
]
} | 7,477 |
||
ImpulsevenSwapV2Factory | core/ImpulsevenSwapV2Pair.sol | 0x4f6703952d3139353a7a8212414a104912c79974 | Solidity | ImpulsevenSwapV2Pair | contract ImpulsevenSwapV2Pair is IImpulsevenSwapV2Pair, ImpulsevenSwapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'ImpulsevenSwapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ImpulsevenSwapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'ImpulsevenSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(10).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'ImpulsevenSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'ImpulsevenSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IImpulsevenSwapV2Callee(to).ImpulsevenSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'ImpulsevenSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'ImpulsevenSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | _update | function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
| // update reserves and, on the first call per block, price accumulators | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://01b3a29875675e373f6a18d5a80c386b8ea850f96117d278cddd4bc206973931 | {
"func_code_index": [
2414,
3286
]
} | 7,478 |
||
ImpulsevenSwapV2Factory | core/ImpulsevenSwapV2Pair.sol | 0x4f6703952d3139353a7a8212414a104912c79974 | Solidity | ImpulsevenSwapV2Pair | contract ImpulsevenSwapV2Pair is IImpulsevenSwapV2Pair, ImpulsevenSwapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'ImpulsevenSwapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ImpulsevenSwapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'ImpulsevenSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(10).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'ImpulsevenSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'ImpulsevenSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IImpulsevenSwapV2Callee(to).ImpulsevenSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'ImpulsevenSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'ImpulsevenSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | _mintFee | function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(10).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
| // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://01b3a29875675e373f6a18d5a80c386b8ea850f96117d278cddd4bc206973931 | {
"func_code_index": [
3371,
4221
]
} | 7,479 |
||
ImpulsevenSwapV2Factory | core/ImpulsevenSwapV2Pair.sol | 0x4f6703952d3139353a7a8212414a104912c79974 | Solidity | ImpulsevenSwapV2Pair | contract ImpulsevenSwapV2Pair is IImpulsevenSwapV2Pair, ImpulsevenSwapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'ImpulsevenSwapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ImpulsevenSwapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'ImpulsevenSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(10).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'ImpulsevenSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'ImpulsevenSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IImpulsevenSwapV2Callee(to).ImpulsevenSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'ImpulsevenSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'ImpulsevenSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | mint | function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
| // this low-level function should be called from a contract which performs important safety checks | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://01b3a29875675e373f6a18d5a80c386b8ea850f96117d278cddd4bc206973931 | {
"func_code_index": [
4328,
5580
]
} | 7,480 |
||
ImpulsevenSwapV2Factory | core/ImpulsevenSwapV2Pair.sol | 0x4f6703952d3139353a7a8212414a104912c79974 | Solidity | ImpulsevenSwapV2Pair | contract ImpulsevenSwapV2Pair is IImpulsevenSwapV2Pair, ImpulsevenSwapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'ImpulsevenSwapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ImpulsevenSwapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'ImpulsevenSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(10).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'ImpulsevenSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'ImpulsevenSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IImpulsevenSwapV2Callee(to).ImpulsevenSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'ImpulsevenSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'ImpulsevenSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | burn | function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
| // this low-level function should be called from a contract which performs important safety checks | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://01b3a29875675e373f6a18d5a80c386b8ea850f96117d278cddd4bc206973931 | {
"func_code_index": [
5687,
7165
]
} | 7,481 |
||
ImpulsevenSwapV2Factory | core/ImpulsevenSwapV2Pair.sol | 0x4f6703952d3139353a7a8212414a104912c79974 | Solidity | ImpulsevenSwapV2Pair | contract ImpulsevenSwapV2Pair is IImpulsevenSwapV2Pair, ImpulsevenSwapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'ImpulsevenSwapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ImpulsevenSwapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'ImpulsevenSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(10).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'ImpulsevenSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'ImpulsevenSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IImpulsevenSwapV2Callee(to).ImpulsevenSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'ImpulsevenSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'ImpulsevenSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | swap | function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'ImpulsevenSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'ImpulsevenSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IImpulsevenSwapV2Callee(to).ImpulsevenSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'ImpulsevenSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'ImpulsevenSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
| // this low-level function should be called from a contract which performs important safety checks | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://01b3a29875675e373f6a18d5a80c386b8ea850f96117d278cddd4bc206973931 | {
"func_code_index": [
7272,
9215
]
} | 7,482 |
||
ImpulsevenSwapV2Factory | core/ImpulsevenSwapV2Pair.sol | 0x4f6703952d3139353a7a8212414a104912c79974 | Solidity | ImpulsevenSwapV2Pair | contract ImpulsevenSwapV2Pair is IImpulsevenSwapV2Pair, ImpulsevenSwapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'ImpulsevenSwapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ImpulsevenSwapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'ImpulsevenSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(10).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'ImpulsevenSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'ImpulsevenSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IImpulsevenSwapV2Callee(to).ImpulsevenSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'ImpulsevenSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'ImpulsevenSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | skim | function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
| // force balances to match reserves | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://01b3a29875675e373f6a18d5a80c386b8ea850f96117d278cddd4bc206973931 | {
"func_code_index": [
9259,
9598
]
} | 7,483 |
||
ImpulsevenSwapV2Factory | core/ImpulsevenSwapV2Pair.sol | 0x4f6703952d3139353a7a8212414a104912c79974 | Solidity | ImpulsevenSwapV2Pair | contract ImpulsevenSwapV2Pair is IImpulsevenSwapV2Pair, ImpulsevenSwapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'ImpulsevenSwapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ImpulsevenSwapV2: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'ImpulsevenSwapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ImpulsevenSwapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IImpulsevenSwapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(10).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'ImpulsevenSwapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ImpulsevenSwapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'ImpulsevenSwapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IImpulsevenSwapV2Callee(to).ImpulsevenSwapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'ImpulsevenSwapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'ImpulsevenSwapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | sync | function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
| // force reserves to match balances | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://01b3a29875675e373f6a18d5a80c386b8ea850f96117d278cddd4bc206973931 | {
"func_code_index": [
9642,
9805
]
} | 7,484 |
||
ethBridge | contracts\erc20.sol | 0xd37c120b2e3c42e130a916e9da24d46b9e9e2a52 | Solidity | Ownable | 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 () public {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @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.
*/ | NatSpecMultiLine | owner | function owner() public view virtual returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | GNU GPLv3 | ipfs://5105c1bc45f254d03c98c2d596b706b8874325e32b2c3301801eb3b14ebe9f44 | {
"func_code_index": [
504,
596
]
} | 7,485 |
ethBridge | contracts\erc20.sol | 0xd37c120b2e3c42e130a916e9da24d46b9e9e2a52 | Solidity | Ownable | 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 () public {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @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.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @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.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | GNU GPLv3 | ipfs://5105c1bc45f254d03c98c2d596b706b8874325e32b2c3301801eb3b14ebe9f44 | {
"func_code_index": [
1155,
1308
]
} | 7,486 |
ethBridge | contracts\erc20.sol | 0xd37c120b2e3c42e130a916e9da24d46b9e9e2a52 | Solidity | Ownable | 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 () public {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @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.
*/ | NatSpecMultiLine | transferOwnership | 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 Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | GNU GPLv3 | ipfs://5105c1bc45f254d03c98c2d596b706b8874325e32b2c3301801eb3b14ebe9f44 | {
"func_code_index": [
1458,
1707
]
} | 7,487 |
ethBridge | contracts\erc20.sol | 0xd37c120b2e3c42e130a916e9da24d46b9e9e2a52 | Solidity | Multiownable | contract Multiownable {
// VARIABLES
uint256 public ownersGeneration;
uint256 public howManyOwnersDecide;
address[] public owners;
bytes32[] public allOperations;
address internal insideCallSender;
uint256 internal insideCallCount;
// Reverse lookup tables for owners and allOperations
mapping(address => uint) public ownersIndices; // Starts from 1
mapping(bytes32 => uint) public allOperationsIndicies;
// Owners voting mask per operations
mapping(bytes32 => uint256) public votesMaskByOperation;
mapping(bytes32 => uint256) public votesCountByOperation;
// EVENTS
event OwnershipTransferred(address[] previousOwners, uint howManyOwnersDecide, address[] newOwners, uint newHowManyOwnersDecide);
event OperationCreated(bytes32 operation, uint howMany, uint ownersCount, address proposer);
event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint ownersCount, address upvoter);
event OperationPerformed(bytes32 operation, uint howMany, uint ownersCount, address performer);
event OperationDownvoted(bytes32 operation, uint votes, uint ownersCount, address downvoter);
event OperationCancelled(bytes32 operation, address lastCanceller);
// ACCESSORS
function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
function ownersCount() public view returns(uint) {
return owners.length;
}
function allOperationsCount() public view returns(uint) {
return allOperations.length;
}
// MODIFIERS
/**
* @dev Allows to perform method by any of the owners
*/
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after many owners call it with the same arguments
*/
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after all owners call it with the same arguments
*/
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after some owners call it with the same arguments
*/
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
// CONSTRUCTOR
constructor() public {
owners.push(msg.sender);
ownersIndices[msg.sender] = 1;
howManyOwnersDecide = 1;
}
// INTERNAL METHODS
/**
* @dev onlyManyOwners modifier helper
*/
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
// If enough owners confirmed the same operation
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
/**
* @dev Used to delete cancelled or performed operation
* @param operation defines which operation to delete
*/
function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
if (index < allOperations.length - 1) { // Not last
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
//allOperations.length-1
allOperations.push(allOperations[allOperations.length-1]);
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
}
// PUBLIC METHODS
/**
* @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations
* @param operation defines which operation to delete
*/
function cancelPending(bytes32 operation) public onlyAnyOwner {
uint ownerIndex = ownersIndices[msg.sender] - 1;
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, "cancelPending: operation not found for this user");
votesMaskByOperation[operation] &= ~(2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] - 1;
votesCountByOperation[operation] = operationVotesCount;
emit OperationDownvoted(operation, operationVotesCount, owners.length, msg.sender);
if (operationVotesCount == 0) {
deleteOperation(operation);
emit OperationCancelled(operation, msg.sender);
}
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
*/
function transferOwnership(address[] memory newOwners) public {
transferOwnershipWithHowMany(newOwners, newOwners.length);
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
* @param newHowManyOwnersDecide defines how many owners can decide
*/
function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners {
require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty");
require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256");
require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0");
require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners");
// Reset owners reverse lookup table
for (uint j = 0; j < owners.length; j++) {
delete ownersIndices[owners[j]];
}
for (uint i = 0; i < newOwners.length; i++) {
require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero");
require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates");
ownersIndices[newOwners[i]] = i + 1;
}
emit OwnershipTransferred(owners, howManyOwnersDecide, newOwners, newHowManyOwnersDecide);
owners = newOwners;
howManyOwnersDecide = newHowManyOwnersDecide;
// allOperations.length = 0;
allOperations.push(allOperations[0]);
ownersGeneration++;
}
} | isOwner | function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
| // ACCESSORS | LineComment | v0.6.12+commit.27d51765 | GNU GPLv3 | ipfs://5105c1bc45f254d03c98c2d596b706b8874325e32b2c3301801eb3b14ebe9f44 | {
"func_code_index": [
1292,
1407
]
} | 7,488 |
||
ethBridge | contracts\erc20.sol | 0xd37c120b2e3c42e130a916e9da24d46b9e9e2a52 | Solidity | Multiownable | contract Multiownable {
// VARIABLES
uint256 public ownersGeneration;
uint256 public howManyOwnersDecide;
address[] public owners;
bytes32[] public allOperations;
address internal insideCallSender;
uint256 internal insideCallCount;
// Reverse lookup tables for owners and allOperations
mapping(address => uint) public ownersIndices; // Starts from 1
mapping(bytes32 => uint) public allOperationsIndicies;
// Owners voting mask per operations
mapping(bytes32 => uint256) public votesMaskByOperation;
mapping(bytes32 => uint256) public votesCountByOperation;
// EVENTS
event OwnershipTransferred(address[] previousOwners, uint howManyOwnersDecide, address[] newOwners, uint newHowManyOwnersDecide);
event OperationCreated(bytes32 operation, uint howMany, uint ownersCount, address proposer);
event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint ownersCount, address upvoter);
event OperationPerformed(bytes32 operation, uint howMany, uint ownersCount, address performer);
event OperationDownvoted(bytes32 operation, uint votes, uint ownersCount, address downvoter);
event OperationCancelled(bytes32 operation, address lastCanceller);
// ACCESSORS
function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
function ownersCount() public view returns(uint) {
return owners.length;
}
function allOperationsCount() public view returns(uint) {
return allOperations.length;
}
// MODIFIERS
/**
* @dev Allows to perform method by any of the owners
*/
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after many owners call it with the same arguments
*/
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after all owners call it with the same arguments
*/
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after some owners call it with the same arguments
*/
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
// CONSTRUCTOR
constructor() public {
owners.push(msg.sender);
ownersIndices[msg.sender] = 1;
howManyOwnersDecide = 1;
}
// INTERNAL METHODS
/**
* @dev onlyManyOwners modifier helper
*/
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
// If enough owners confirmed the same operation
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
/**
* @dev Used to delete cancelled or performed operation
* @param operation defines which operation to delete
*/
function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
if (index < allOperations.length - 1) { // Not last
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
//allOperations.length-1
allOperations.push(allOperations[allOperations.length-1]);
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
}
// PUBLIC METHODS
/**
* @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations
* @param operation defines which operation to delete
*/
function cancelPending(bytes32 operation) public onlyAnyOwner {
uint ownerIndex = ownersIndices[msg.sender] - 1;
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, "cancelPending: operation not found for this user");
votesMaskByOperation[operation] &= ~(2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] - 1;
votesCountByOperation[operation] = operationVotesCount;
emit OperationDownvoted(operation, operationVotesCount, owners.length, msg.sender);
if (operationVotesCount == 0) {
deleteOperation(operation);
emit OperationCancelled(operation, msg.sender);
}
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
*/
function transferOwnership(address[] memory newOwners) public {
transferOwnershipWithHowMany(newOwners, newOwners.length);
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
* @param newHowManyOwnersDecide defines how many owners can decide
*/
function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners {
require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty");
require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256");
require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0");
require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners");
// Reset owners reverse lookup table
for (uint j = 0; j < owners.length; j++) {
delete ownersIndices[owners[j]];
}
for (uint i = 0; i < newOwners.length; i++) {
require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero");
require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates");
ownersIndices[newOwners[i]] = i + 1;
}
emit OwnershipTransferred(owners, howManyOwnersDecide, newOwners, newHowManyOwnersDecide);
owners = newOwners;
howManyOwnersDecide = newHowManyOwnersDecide;
// allOperations.length = 0;
allOperations.push(allOperations[0]);
ownersGeneration++;
}
} | checkHowManyOwners | function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
// If enough owners confirmed the same operation
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
| /**
* @dev onlyManyOwners modifier helper
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | GNU GPLv3 | ipfs://5105c1bc45f254d03c98c2d596b706b8874325e32b2c3301801eb3b14ebe9f44 | {
"func_code_index": [
4258,
5784
]
} | 7,489 |
||
ethBridge | contracts\erc20.sol | 0xd37c120b2e3c42e130a916e9da24d46b9e9e2a52 | Solidity | Multiownable | contract Multiownable {
// VARIABLES
uint256 public ownersGeneration;
uint256 public howManyOwnersDecide;
address[] public owners;
bytes32[] public allOperations;
address internal insideCallSender;
uint256 internal insideCallCount;
// Reverse lookup tables for owners and allOperations
mapping(address => uint) public ownersIndices; // Starts from 1
mapping(bytes32 => uint) public allOperationsIndicies;
// Owners voting mask per operations
mapping(bytes32 => uint256) public votesMaskByOperation;
mapping(bytes32 => uint256) public votesCountByOperation;
// EVENTS
event OwnershipTransferred(address[] previousOwners, uint howManyOwnersDecide, address[] newOwners, uint newHowManyOwnersDecide);
event OperationCreated(bytes32 operation, uint howMany, uint ownersCount, address proposer);
event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint ownersCount, address upvoter);
event OperationPerformed(bytes32 operation, uint howMany, uint ownersCount, address performer);
event OperationDownvoted(bytes32 operation, uint votes, uint ownersCount, address downvoter);
event OperationCancelled(bytes32 operation, address lastCanceller);
// ACCESSORS
function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
function ownersCount() public view returns(uint) {
return owners.length;
}
function allOperationsCount() public view returns(uint) {
return allOperations.length;
}
// MODIFIERS
/**
* @dev Allows to perform method by any of the owners
*/
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after many owners call it with the same arguments
*/
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after all owners call it with the same arguments
*/
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after some owners call it with the same arguments
*/
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
// CONSTRUCTOR
constructor() public {
owners.push(msg.sender);
ownersIndices[msg.sender] = 1;
howManyOwnersDecide = 1;
}
// INTERNAL METHODS
/**
* @dev onlyManyOwners modifier helper
*/
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
// If enough owners confirmed the same operation
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
/**
* @dev Used to delete cancelled or performed operation
* @param operation defines which operation to delete
*/
function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
if (index < allOperations.length - 1) { // Not last
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
//allOperations.length-1
allOperations.push(allOperations[allOperations.length-1]);
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
}
// PUBLIC METHODS
/**
* @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations
* @param operation defines which operation to delete
*/
function cancelPending(bytes32 operation) public onlyAnyOwner {
uint ownerIndex = ownersIndices[msg.sender] - 1;
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, "cancelPending: operation not found for this user");
votesMaskByOperation[operation] &= ~(2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] - 1;
votesCountByOperation[operation] = operationVotesCount;
emit OperationDownvoted(operation, operationVotesCount, owners.length, msg.sender);
if (operationVotesCount == 0) {
deleteOperation(operation);
emit OperationCancelled(operation, msg.sender);
}
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
*/
function transferOwnership(address[] memory newOwners) public {
transferOwnershipWithHowMany(newOwners, newOwners.length);
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
* @param newHowManyOwnersDecide defines how many owners can decide
*/
function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners {
require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty");
require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256");
require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0");
require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners");
// Reset owners reverse lookup table
for (uint j = 0; j < owners.length; j++) {
delete ownersIndices[owners[j]];
}
for (uint i = 0; i < newOwners.length; i++) {
require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero");
require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates");
ownersIndices[newOwners[i]] = i + 1;
}
emit OwnershipTransferred(owners, howManyOwnersDecide, newOwners, newHowManyOwnersDecide);
owners = newOwners;
howManyOwnersDecide = newHowManyOwnersDecide;
// allOperations.length = 0;
allOperations.push(allOperations[0]);
ownersGeneration++;
}
} | deleteOperation | function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
if (index < allOperations.length - 1) { // Not last
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
//allOperations.length-1
allOperations.push(allOperations[allOperations.length-1]);
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
}
| /**
* @dev Used to delete cancelled or performed operation
* @param operation defines which operation to delete
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | GNU GPLv3 | ipfs://5105c1bc45f254d03c98c2d596b706b8874325e32b2c3301801eb3b14ebe9f44 | {
"func_code_index": [
5922,
6512
]
} | 7,490 |
||
ethBridge | contracts\erc20.sol | 0xd37c120b2e3c42e130a916e9da24d46b9e9e2a52 | Solidity | Multiownable | contract Multiownable {
// VARIABLES
uint256 public ownersGeneration;
uint256 public howManyOwnersDecide;
address[] public owners;
bytes32[] public allOperations;
address internal insideCallSender;
uint256 internal insideCallCount;
// Reverse lookup tables for owners and allOperations
mapping(address => uint) public ownersIndices; // Starts from 1
mapping(bytes32 => uint) public allOperationsIndicies;
// Owners voting mask per operations
mapping(bytes32 => uint256) public votesMaskByOperation;
mapping(bytes32 => uint256) public votesCountByOperation;
// EVENTS
event OwnershipTransferred(address[] previousOwners, uint howManyOwnersDecide, address[] newOwners, uint newHowManyOwnersDecide);
event OperationCreated(bytes32 operation, uint howMany, uint ownersCount, address proposer);
event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint ownersCount, address upvoter);
event OperationPerformed(bytes32 operation, uint howMany, uint ownersCount, address performer);
event OperationDownvoted(bytes32 operation, uint votes, uint ownersCount, address downvoter);
event OperationCancelled(bytes32 operation, address lastCanceller);
// ACCESSORS
function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
function ownersCount() public view returns(uint) {
return owners.length;
}
function allOperationsCount() public view returns(uint) {
return allOperations.length;
}
// MODIFIERS
/**
* @dev Allows to perform method by any of the owners
*/
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after many owners call it with the same arguments
*/
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after all owners call it with the same arguments
*/
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after some owners call it with the same arguments
*/
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
// CONSTRUCTOR
constructor() public {
owners.push(msg.sender);
ownersIndices[msg.sender] = 1;
howManyOwnersDecide = 1;
}
// INTERNAL METHODS
/**
* @dev onlyManyOwners modifier helper
*/
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
// If enough owners confirmed the same operation
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
/**
* @dev Used to delete cancelled or performed operation
* @param operation defines which operation to delete
*/
function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
if (index < allOperations.length - 1) { // Not last
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
//allOperations.length-1
allOperations.push(allOperations[allOperations.length-1]);
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
}
// PUBLIC METHODS
/**
* @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations
* @param operation defines which operation to delete
*/
function cancelPending(bytes32 operation) public onlyAnyOwner {
uint ownerIndex = ownersIndices[msg.sender] - 1;
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, "cancelPending: operation not found for this user");
votesMaskByOperation[operation] &= ~(2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] - 1;
votesCountByOperation[operation] = operationVotesCount;
emit OperationDownvoted(operation, operationVotesCount, owners.length, msg.sender);
if (operationVotesCount == 0) {
deleteOperation(operation);
emit OperationCancelled(operation, msg.sender);
}
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
*/
function transferOwnership(address[] memory newOwners) public {
transferOwnershipWithHowMany(newOwners, newOwners.length);
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
* @param newHowManyOwnersDecide defines how many owners can decide
*/
function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners {
require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty");
require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256");
require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0");
require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners");
// Reset owners reverse lookup table
for (uint j = 0; j < owners.length; j++) {
delete ownersIndices[owners[j]];
}
for (uint i = 0; i < newOwners.length; i++) {
require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero");
require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates");
ownersIndices[newOwners[i]] = i + 1;
}
emit OwnershipTransferred(owners, howManyOwnersDecide, newOwners, newHowManyOwnersDecide);
owners = newOwners;
howManyOwnersDecide = newHowManyOwnersDecide;
// allOperations.length = 0;
allOperations.push(allOperations[0]);
ownersGeneration++;
}
} | cancelPending | function cancelPending(bytes32 operation) public onlyAnyOwner {
uint ownerIndex = ownersIndices[msg.sender] - 1;
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, "cancelPending: operation not found for this user");
votesMaskByOperation[operation] &= ~(2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] - 1;
votesCountByOperation[operation] = operationVotesCount;
emit OperationDownvoted(operation, operationVotesCount, owners.length, msg.sender);
if (operationVotesCount == 0) {
deleteOperation(operation);
emit OperationCancelled(operation, msg.sender);
}
}
| /**
* @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations
* @param operation defines which operation to delete
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | GNU GPLv3 | ipfs://5105c1bc45f254d03c98c2d596b706b8874325e32b2c3301801eb3b14ebe9f44 | {
"func_code_index": [
6708,
7421
]
} | 7,491 |
||
ethBridge | contracts\erc20.sol | 0xd37c120b2e3c42e130a916e9da24d46b9e9e2a52 | Solidity | Multiownable | contract Multiownable {
// VARIABLES
uint256 public ownersGeneration;
uint256 public howManyOwnersDecide;
address[] public owners;
bytes32[] public allOperations;
address internal insideCallSender;
uint256 internal insideCallCount;
// Reverse lookup tables for owners and allOperations
mapping(address => uint) public ownersIndices; // Starts from 1
mapping(bytes32 => uint) public allOperationsIndicies;
// Owners voting mask per operations
mapping(bytes32 => uint256) public votesMaskByOperation;
mapping(bytes32 => uint256) public votesCountByOperation;
// EVENTS
event OwnershipTransferred(address[] previousOwners, uint howManyOwnersDecide, address[] newOwners, uint newHowManyOwnersDecide);
event OperationCreated(bytes32 operation, uint howMany, uint ownersCount, address proposer);
event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint ownersCount, address upvoter);
event OperationPerformed(bytes32 operation, uint howMany, uint ownersCount, address performer);
event OperationDownvoted(bytes32 operation, uint votes, uint ownersCount, address downvoter);
event OperationCancelled(bytes32 operation, address lastCanceller);
// ACCESSORS
function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
function ownersCount() public view returns(uint) {
return owners.length;
}
function allOperationsCount() public view returns(uint) {
return allOperations.length;
}
// MODIFIERS
/**
* @dev Allows to perform method by any of the owners
*/
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after many owners call it with the same arguments
*/
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after all owners call it with the same arguments
*/
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after some owners call it with the same arguments
*/
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
// CONSTRUCTOR
constructor() public {
owners.push(msg.sender);
ownersIndices[msg.sender] = 1;
howManyOwnersDecide = 1;
}
// INTERNAL METHODS
/**
* @dev onlyManyOwners modifier helper
*/
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
// If enough owners confirmed the same operation
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
/**
* @dev Used to delete cancelled or performed operation
* @param operation defines which operation to delete
*/
function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
if (index < allOperations.length - 1) { // Not last
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
//allOperations.length-1
allOperations.push(allOperations[allOperations.length-1]);
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
}
// PUBLIC METHODS
/**
* @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations
* @param operation defines which operation to delete
*/
function cancelPending(bytes32 operation) public onlyAnyOwner {
uint ownerIndex = ownersIndices[msg.sender] - 1;
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, "cancelPending: operation not found for this user");
votesMaskByOperation[operation] &= ~(2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] - 1;
votesCountByOperation[operation] = operationVotesCount;
emit OperationDownvoted(operation, operationVotesCount, owners.length, msg.sender);
if (operationVotesCount == 0) {
deleteOperation(operation);
emit OperationCancelled(operation, msg.sender);
}
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
*/
function transferOwnership(address[] memory newOwners) public {
transferOwnershipWithHowMany(newOwners, newOwners.length);
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
* @param newHowManyOwnersDecide defines how many owners can decide
*/
function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners {
require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty");
require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256");
require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0");
require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners");
// Reset owners reverse lookup table
for (uint j = 0; j < owners.length; j++) {
delete ownersIndices[owners[j]];
}
for (uint i = 0; i < newOwners.length; i++) {
require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero");
require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates");
ownersIndices[newOwners[i]] = i + 1;
}
emit OwnershipTransferred(owners, howManyOwnersDecide, newOwners, newHowManyOwnersDecide);
owners = newOwners;
howManyOwnersDecide = newHowManyOwnersDecide;
// allOperations.length = 0;
allOperations.push(allOperations[0]);
ownersGeneration++;
}
} | transferOwnership | function transferOwnership(address[] memory newOwners) public {
transferOwnershipWithHowMany(newOwners, newOwners.length);
}
| /**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | GNU GPLv3 | ipfs://5105c1bc45f254d03c98c2d596b706b8874325e32b2c3301801eb3b14ebe9f44 | {
"func_code_index": [
7552,
7695
]
} | 7,492 |
||
ethBridge | contracts\erc20.sol | 0xd37c120b2e3c42e130a916e9da24d46b9e9e2a52 | Solidity | Multiownable | contract Multiownable {
// VARIABLES
uint256 public ownersGeneration;
uint256 public howManyOwnersDecide;
address[] public owners;
bytes32[] public allOperations;
address internal insideCallSender;
uint256 internal insideCallCount;
// Reverse lookup tables for owners and allOperations
mapping(address => uint) public ownersIndices; // Starts from 1
mapping(bytes32 => uint) public allOperationsIndicies;
// Owners voting mask per operations
mapping(bytes32 => uint256) public votesMaskByOperation;
mapping(bytes32 => uint256) public votesCountByOperation;
// EVENTS
event OwnershipTransferred(address[] previousOwners, uint howManyOwnersDecide, address[] newOwners, uint newHowManyOwnersDecide);
event OperationCreated(bytes32 operation, uint howMany, uint ownersCount, address proposer);
event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint ownersCount, address upvoter);
event OperationPerformed(bytes32 operation, uint howMany, uint ownersCount, address performer);
event OperationDownvoted(bytes32 operation, uint votes, uint ownersCount, address downvoter);
event OperationCancelled(bytes32 operation, address lastCanceller);
// ACCESSORS
function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
function ownersCount() public view returns(uint) {
return owners.length;
}
function allOperationsCount() public view returns(uint) {
return allOperations.length;
}
// MODIFIERS
/**
* @dev Allows to perform method by any of the owners
*/
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after many owners call it with the same arguments
*/
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after all owners call it with the same arguments
*/
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after some owners call it with the same arguments
*/
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
// CONSTRUCTOR
constructor() public {
owners.push(msg.sender);
ownersIndices[msg.sender] = 1;
howManyOwnersDecide = 1;
}
// INTERNAL METHODS
/**
* @dev onlyManyOwners modifier helper
*/
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
// If enough owners confirmed the same operation
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
/**
* @dev Used to delete cancelled or performed operation
* @param operation defines which operation to delete
*/
function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
if (index < allOperations.length - 1) { // Not last
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
//allOperations.length-1
allOperations.push(allOperations[allOperations.length-1]);
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
}
// PUBLIC METHODS
/**
* @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations
* @param operation defines which operation to delete
*/
function cancelPending(bytes32 operation) public onlyAnyOwner {
uint ownerIndex = ownersIndices[msg.sender] - 1;
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, "cancelPending: operation not found for this user");
votesMaskByOperation[operation] &= ~(2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] - 1;
votesCountByOperation[operation] = operationVotesCount;
emit OperationDownvoted(operation, operationVotesCount, owners.length, msg.sender);
if (operationVotesCount == 0) {
deleteOperation(operation);
emit OperationCancelled(operation, msg.sender);
}
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
*/
function transferOwnership(address[] memory newOwners) public {
transferOwnershipWithHowMany(newOwners, newOwners.length);
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
* @param newHowManyOwnersDecide defines how many owners can decide
*/
function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners {
require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty");
require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256");
require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0");
require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners");
// Reset owners reverse lookup table
for (uint j = 0; j < owners.length; j++) {
delete ownersIndices[owners[j]];
}
for (uint i = 0; i < newOwners.length; i++) {
require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero");
require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates");
ownersIndices[newOwners[i]] = i + 1;
}
emit OwnershipTransferred(owners, howManyOwnersDecide, newOwners, newHowManyOwnersDecide);
owners = newOwners;
howManyOwnersDecide = newHowManyOwnersDecide;
// allOperations.length = 0;
allOperations.push(allOperations[0]);
ownersGeneration++;
}
} | transferOwnershipWithHowMany | function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners {
require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty");
require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256");
require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0");
require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners");
// Reset owners reverse lookup table
for (uint j = 0; j < owners.length; j++) {
delete ownersIndices[owners[j]];
}
for (uint i = 0; i < newOwners.length; i++) {
require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero");
require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates");
ownersIndices[newOwners[i]] = i + 1;
}
emit OwnershipTransferred(owners, howManyOwnersDecide, newOwners, newHowManyOwnersDecide);
owners = newOwners;
howManyOwnersDecide = newHowManyOwnersDecide;
// allOperations.length = 0;
allOperations.push(allOperations[0]);
ownersGeneration++;
}
| /**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
* @param newHowManyOwnersDecide defines how many owners can decide
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | GNU GPLv3 | ipfs://5105c1bc45f254d03c98c2d596b706b8874325e32b2c3301801eb3b14ebe9f44 | {
"func_code_index": [
7898,
9308
]
} | 7,493 |
||
OpenVibes | OpenVibes.sol | 0xf3fcd0f025c21f087dbeb754516d2ad8279140fc | Solidity | IERC165 | interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | /**
* @dev Interface of the 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}.
*/ | NatSpecMultiLine | supportsInterface | function supportsInterface(bytes4 interfaceId) external view returns (bool);
| /**
* @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.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://553cd8e6a1f89ccf53271ac99799e3d21130ba1d83156e08546f59670d720b69 | {
"func_code_index": [
374,
455
]
} | 7,494 |
OpenVibes | OpenVibes.sol | 0xf3fcd0f025c21f087dbeb754516d2ad8279140fc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address owner) external view returns (uint256 balance);
| /**
* @dev Returns the number of tokens in ``owner``'s account.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://553cd8e6a1f89ccf53271ac99799e3d21130ba1d83156e08546f59670d720b69 | {
"func_code_index": [
719,
798
]
} | 7,495 |
OpenVibes | OpenVibes.sol | 0xf3fcd0f025c21f087dbeb754516d2ad8279140fc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | ownerOf | function ownerOf(uint256 tokenId) external view returns (address owner);
| /**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://553cd8e6a1f89ccf53271ac99799e3d21130ba1d83156e08546f59670d720b69 | {
"func_code_index": [
944,
1021
]
} | 7,496 |
OpenVibes | OpenVibes.sol | 0xf3fcd0f025c21f087dbeb754516d2ad8279140fc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | safeTransferFrom | function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
| /**
* @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.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://553cd8e6a1f89ccf53271ac99799e3d21130ba1d83156e08546f59670d720b69 | {
"func_code_index": [
1733,
1850
]
} | 7,497 |
OpenVibes | OpenVibes.sol | 0xf3fcd0f025c21f087dbeb754516d2ad8279140fc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(
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.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://553cd8e6a1f89ccf53271ac99799e3d21130ba1d83156e08546f59670d720b69 | {
"func_code_index": [
2376,
2489
]
} | 7,498 |
OpenVibes | OpenVibes.sol | 0xf3fcd0f025c21f087dbeb754516d2ad8279140fc | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | approve | function approve(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.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://553cd8e6a1f89ccf53271ac99799e3d21130ba1d83156e08546f59670d720b69 | {
"func_code_index": [
2962,
3022
]
} | 7,499 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.