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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PartySheepClub | @openzeppelin/contracts/access/Ownable.sol | 0xe9a4f318b12c890ca93b1da0140394030672b0ad | 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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | /**
* @dev Contract module 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.8.7+commit.e28d00a7 | MIT | ipfs://f1cb149f7f6599c786e934dd45da6969904fe8383c1f4d2481900bf156945d1e | {
"func_code_index": [
399,
491
]
} | 7,507 |
PartySheepClub | @openzeppelin/contracts/access/Ownable.sol | 0xe9a4f318b12c890ca93b1da0140394030672b0ad | 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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | /**
* @dev Contract module 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 {
_setOwner(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.8.7+commit.e28d00a7 | MIT | ipfs://f1cb149f7f6599c786e934dd45da6969904fe8383c1f4d2481900bf156945d1e | {
"func_code_index": [
1050,
1149
]
} | 7,508 |
PartySheepClub | @openzeppelin/contracts/access/Ownable.sol | 0xe9a4f318b12c890ca93b1da0140394030672b0ad | 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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | /**
* @dev Contract module 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");
_setOwner(newOwner);
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://f1cb149f7f6599c786e934dd45da6969904fe8383c1f4d2481900bf156945d1e | {
"func_code_index": [
1299,
1496
]
} | 7,509 |
PartySheepClub | @openzeppelin/contracts/access/Ownable.sol | 0xe9a4f318b12c890ca93b1da0140394030672b0ad | Solidity | PartySheepClub | contract PartySheepClub is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.08 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmount = 20;
bool public paused = false;
bool public revealed = false;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner() {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
} | _baseURI | function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
| // internal | LineComment | v0.8.7+commit.e28d00a7 | MIT | ipfs://f1cb149f7f6599c786e934dd45da6969904fe8383c1f4d2481900bf156945d1e | {
"func_code_index": [
630,
735
]
} | 7,510 |
||
PartySheepClub | @openzeppelin/contracts/access/Ownable.sol | 0xe9a4f318b12c890ca93b1da0140394030672b0ad | Solidity | PartySheepClub | contract PartySheepClub is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.08 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmount = 20;
bool public paused = false;
bool public revealed = false;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner() {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
} | mint | function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
| // public | LineComment | v0.8.7+commit.e28d00a7 | MIT | ipfs://f1cb149f7f6599c786e934dd45da6969904fe8383c1f4d2481900bf156945d1e | {
"func_code_index": [
751,
1187
]
} | 7,511 |
||
PartySheepClub | @openzeppelin/contracts/access/Ownable.sol | 0xe9a4f318b12c890ca93b1da0140394030672b0ad | Solidity | PartySheepClub | contract PartySheepClub is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.08 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmount = 20;
bool public paused = false;
bool public revealed = false;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner() {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
} | reveal | function reveal() public onlyOwner() {
revealed = true;
}
| //only owner | LineComment | v0.8.7+commit.e28d00a7 | MIT | ipfs://f1cb149f7f6599c786e934dd45da6969904fe8383c1f4d2481900bf156945d1e | {
"func_code_index": [
2063,
2133
]
} | 7,512 |
||
RollsRoyce | RollsRoyce.sol | 0x6d150887670539be19ec85835db4db89532f1ff9 | Solidity | RollsRoyce | contract RollsRoyce {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Initializes contract with initial supply tokens to the creator of the contract */
function RollsRoyce() {
initialSupply = 5000000;
name ="RollsRoyce";
decimals = 1;
symbol = "RRC";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
} | RollsRoyce | function RollsRoyce() {
initialSupply = 5000000;
name ="RollsRoyce";
decimals = 1;
symbol = "RRC";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
| /* Initializes contract with initial supply tokens to the creator of the contract */ | Comment | v0.4.19+commit.c4cbbb05 | bzzr://d3e36ec256f3c4880e775436be47b3cc3ab34dfc2a78985ee4161d1ec6ee4267 | {
"func_code_index": [
529,
911
]
} | 7,513 |
|||
RollsRoyce | RollsRoyce.sol | 0x6d150887670539be19ec85835db4db89532f1ff9 | Solidity | RollsRoyce | contract RollsRoyce {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Initializes contract with initial supply tokens to the creator of the contract */
function RollsRoyce() {
initialSupply = 5000000;
name ="RollsRoyce";
decimals = 1;
symbol = "RRC";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
} | transfer | function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
| /* Send coins */ | Comment | v0.4.19+commit.c4cbbb05 | bzzr://d3e36ec256f3c4880e775436be47b3cc3ab34dfc2a78985ee4161d1ec6ee4267 | {
"func_code_index": [
936,
1370
]
} | 7,514 |
|||
RollsRoyce | RollsRoyce.sol | 0x6d150887670539be19ec85835db4db89532f1ff9 | Solidity | RollsRoyce | contract RollsRoyce {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Initializes contract with initial supply tokens to the creator of the contract */
function RollsRoyce() {
initialSupply = 5000000;
name ="RollsRoyce";
decimals = 1;
symbol = "RRC";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
} | function () {
throw; // Prevents accidental sending of ether
}
| /* This unnamed function is called whenever someone tries to send ether to it */ | Comment | v0.4.19+commit.c4cbbb05 | bzzr://d3e36ec256f3c4880e775436be47b3cc3ab34dfc2a78985ee4161d1ec6ee4267 | {
"func_code_index": [
1481,
1566
]
} | 7,515 |
||||
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | update | function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
| /// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
1704,
3284
]
} | 7,516 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | setMaxPriceDeviation | function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
| /// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
3525,
3733
]
} | 7,517 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | setMaxSpread | function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
| /// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
3937,
4097
]
} | 7,518 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | setRegistry | function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
| /// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
4220,
4385
]
} | 7,519 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | setUpdater | function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
| /// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
4505,
4653
]
} | 7,520 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | getPrices | function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
| /// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_ | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
4925,
5357
]
} | 7,521 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | hasValidPrices | function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
| /// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false) | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
5597,
5899
]
} | 7,522 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | getOrderPriceInfo | function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
| /// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
6241,
6592
]
} | 7,523 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | convertQuantity | function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
| /// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
6917,
7446
]
} | 7,524 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | getPrice | function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
| /// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
7796,
8024
]
} | 7,525 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | hasValidPrice | function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
| /// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
8208,
8530
]
} | 7,526 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | getReferencePriceInfo | function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
| /// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
8950,
9411
]
} | 7,527 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | getKyberPrice | function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
| /// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
9760,
11725
]
} | 7,528 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | __getKyberMaskAsset | function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
| /// @dev Return Kyber ETH asset symbol if _asset is WETH | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
11815,
12058
]
} | 7,529 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | __getRawReferencePriceInfo | function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
| /// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0) | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
12210,
12874
]
} | 7,530 |
KyberPriceFeed | ./src/prices/KyberPriceFeed.sol | 0x10a285ea8b9e0ff92a2de4ecf961293a6999f7e6 | Solidity | KyberPriceFeed | contract KyberPriceFeed is DSMath {
event MaxPriceDeviationSet(uint256 maxPriceDeviation);
event MaxSpreadSet(uint256 maxSpread);
event PricesUpdated(address[] assets, uint256[] prices);
event RegistrySet(address newRegistry);
event UpdaterSet(address updater);
uint8 public constant KYBER_PRECISION = 18;
uint32 public constant VALIDITY_INTERVAL = 2 days;
address public KYBER_NETWORK_PROXY;
address public QUOTE_ASSET;
uint256 public lastUpdate;
uint256 public maxPriceDeviation; // percent, expressed as a uint256 (fraction of 10^18)
uint256 public maxSpread;
address public updater;
mapping (address => uint256) public prices;
IRegistry public registry;
constructor(
address _registry,
address _kyberNetworkProxy,
uint256 _maxSpread,
address _quoteAsset,
uint256 _maxPriceDeviation
)
public
{
registry = IRegistry(_registry);
KYBER_NETWORK_PROXY = _kyberNetworkProxy;
maxSpread = _maxSpread;
QUOTE_ASSET = _quoteAsset;
maxPriceDeviation = _maxPriceDeviation;
updater = registry.owner();
}
modifier onlyRegistryOwner() {
require(msg.sender == registry.owner(), "Only registry owner can do this");
_;
}
// EXTERNAL FUNCTIONS
/// @notice Update prices for registered assets
/// @dev Stores zero as a convention for invalid price
/// @param _saneAssets Asset addresses (must match assets array from getRegisteredAssets)
/// @param _sanePrices Asset price hints (checked against prices from Kyber)
/// @param _failIfInvalid Whether to abort the update if an invalid price appears
function update(
address[] calldata _saneAssets,
uint256[] calldata _sanePrices,
bool _failIfInvalid
) external {
require(
msg.sender == registry.owner() || msg.sender == updater,
"update: Only registry owner or updater can call"
);
address[] memory registeredAssets = registry.getRegisteredAssets();
require(
keccak256(abi.encodePacked(_saneAssets)) ==
keccak256(abi.encodePacked(registeredAssets)),
"update: Passed and registered assets are not identical"
);
uint256[] memory newPrices = new uint256[](_saneAssets.length);
for (uint256 i; i < _saneAssets.length; i++) {
bool isValid;
uint256 kyberPrice;
if (_saneAssets[i] == QUOTE_ASSET) {
isValid = true;
kyberPrice = 1 ether;
} else {
(isValid, kyberPrice) = getKyberPrice(_saneAssets[i], QUOTE_ASSET);
}
require(
__priceIsSane(kyberPrice, _sanePrices[i]),
"update: Kyber price deviates too much from maxPriceDeviation"
);
if (_failIfInvalid) {
require(
isValid,
"update: Aborting due to invalid price"
);
}
newPrices[i] = isValid ? kyberPrice : 0;
prices[_saneAssets[i]] = newPrices[i];
}
lastUpdate = block.timestamp;
emit PricesUpdated(_saneAssets, newPrices);
}
/// @notice Update maximum price deviation between price hints and Kyber price
/// @notice Price deviation becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxPriceDeviation New maximum price deviation
function setMaxPriceDeviation(uint256 _newMaxPriceDeviation) external onlyRegistryOwner {
maxPriceDeviation = _newMaxPriceDeviation;
emit MaxPriceDeviationSet(_newMaxPriceDeviation);
}
/// @notice Update maximum spread for prices derived from Kyber
/// @notice Max spread becomes a % when divided by 10^18 (e.g. 10^17 becomes 10%)
/// @param _newMaxSpread New maximum spread
function setMaxSpread(uint256 _newMaxSpread) external onlyRegistryOwner {
maxSpread = _newMaxSpread;
emit MaxSpreadSet(_newMaxSpread);
}
/// @notice Update this feed's Registry reference
/// @param _newRegistry New Registry this feed should point to
function setRegistry(address _newRegistry) external onlyRegistryOwner {
registry = IRegistry(_newRegistry);
emit RegistrySet(_newRegistry);
}
/// @notice Update this feed's designated updater
/// @param _newUpdater New designated updater for this feed
function setUpdater(address _newUpdater) external onlyRegistryOwner {
updater = _newUpdater;
emit UpdaterSet(_newUpdater);
}
// EXTERNAL VIEW FUNCTIONS
/// @notice Return getPrice for each of _assets
/// @param _assets Assets for which prices should be returned
/// @return prices_ Prices for each of the assets_
/// @return timestamps_ Update times for each of the assets_
function getPrices(address[] calldata _assets)
external
view
returns (uint256[] memory prices_, uint256[] memory timestamps_)
{
prices_ = new uint256[](_assets.length);
timestamps_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
(prices_[i], timestamps_[i]) = getPrice(_assets[i]);
}
return (prices_, timestamps_);
}
/// @notice Whether each of the _assets is registered and has a fresh price
/// @param _assets Assets for which validity information should be returned
/// @return allValid_ Validity of prices for each of _assets (true/false)
function hasValidPrices(address[] calldata _assets)
external
view
returns (bool allValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!hasValidPrice(_assets[i])) {
return false;
}
}
return true;
}
/// @notice Returns price as determined by an order
/// @param _sellAsset Address of the asset to be sold
/// @param _sellQuantity Quantity (in base units) of _sellAsset being sold
/// @param _buyQuantity Quantity (in base units) of _buyAsset being bought
/// @return orderPrice_ Price determined by buy/sell quantities
function getOrderPriceInfo(
address _sellAsset,
uint256 _sellQuantity,
uint256 _buyQuantity
)
external
view
returns (uint256 orderPrice_)
{
orderPrice_ = mul(
_buyQuantity,
10 ** uint256(ERC20WithFields(_sellAsset).decimals())
) / _sellQuantity;
}
/// @notice Get quantity of _toAsset equal in value to some quantity of _fromAsset
/// @param _fromAssetQuantity Amount of _fromAsset
/// @param _fromAsset Address of _fromAsset
/// @param _toAsset Address of _toAsset
/// @return toAssetQuantity_ Amount of _toAsset equal in value to _fromAssetQuantity
function convertQuantity(
uint256 _fromAssetQuantity,
address _fromAsset,
address _toAsset
)
external
view
returns (uint256 toAssetQuantity_)
{
uint256 fromAssetPrice;
(fromAssetPrice,) = getReferencePriceInfo(_fromAsset, _toAsset);
uint256 fromAssetDecimals = ERC20WithFields(_fromAsset).decimals();
toAssetQuantity_ = mul(
_fromAssetQuantity,
fromAssetPrice
) / (10 ** uint256(fromAssetDecimals));
}
// PUBLIC FUNCTIONS
/// @notice Gets price of an asset times 10^assetDecimals
/// @dev Asset must be registered
/// @param _asset Asset for which price should be returned
/// @return price_ Formatting: exchangePrice * 10^decimals (to avoid floating point)
/// @return timestamp_ When the asset's price was last updated
function getPrice(address _asset)
public
view
returns (uint256 price_, uint256 timestamp_)
{
(price_,) = getReferencePriceInfo(_asset, QUOTE_ASSET);
timestamp_ = lastUpdate;
}
/// @notice Whether an asset is registered and has a fresh price
/// @param _asset Asset to check for a valid price
/// @return isValid_ whether price of _asset is valid
function hasValidPrice(address _asset)
public
view
returns (bool isValid_)
{
bool isRegistered = registry.assetIsRegistered(_asset);
bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);
isValid_ = prices[_asset] != 0 && isRegistered && isFresh;
}
/// @notice Get price of an asset in terms of some quote asset, plus the quote asset's decimals
/// @notice This function reverts if either the base or quote have invalid prices
/// @param _baseAsset Address of base asset
/// @param _quoteAsset Address of quote asset
/// @return referencePrice_ Quantity of _quoteAsset per whole _baseAsset
/// @return decimals_ Decimal places for _quoteAsset
function getReferencePriceInfo(address _baseAsset, address _quoteAsset)
public
view
returns (uint256 referencePrice_, uint256 decimals_)
{
bool isValid;
(
isValid,
referencePrice_,
decimals_
) = __getRawReferencePriceInfo(_baseAsset, _quoteAsset);
require(isValid, "getReferencePriceInfo: Price is not valid");
return (referencePrice_, decimals_);
}
/// @notice Returns validity and price for some pair of assets from Kyber
/// @param _baseAsset Address of base asset from the pair
/// @param _quoteAsset Address of quote asset from the pair
/// @return validity_ Whether the price for this pair is valid
/// @return kyberPrice_ The price of _baseAsset in terms of _quoteAsset
function getKyberPrice(address _baseAsset, address _quoteAsset)
public
view
returns (bool validity_, uint256 kyberPrice_)
{
uint256 bidRate;
uint256 bidRateOfReversePair;
(bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_baseAsset),
__getKyberMaskAsset(_quoteAsset),
registry.getReserveMin(_baseAsset)
);
(bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(
__getKyberMaskAsset(_quoteAsset),
__getKyberMaskAsset(_baseAsset),
registry.getReserveMin(_quoteAsset)
);
if (bidRate == 0 || bidRateOfReversePair == 0) {
return (false, 0); // return early and avoid revert
}
uint256 askRate = 10 ** (uint256(KYBER_PRECISION) * 2) / bidRateOfReversePair;
/**
Average the bid/ask prices:
avgPriceFromKyber = (bidRate + askRate) / 2
kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision
or, rearranged:
kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision
*/
kyberPrice_ = mul(
add(bidRate, askRate),
10 ** uint256(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)
) / mul(2, 10 ** uint256(KYBER_PRECISION));
// Find the "quoted spread", to inform caller whether it is below maximum
uint256 spreadFromKyber;
if (bidRate > askRate) {
spreadFromKyber = 0; // crossed market condition
} else {
spreadFromKyber = mul(
sub(askRate, bidRate),
10 ** uint256(KYBER_PRECISION)
) / askRate;
}
validity_ = spreadFromKyber <= maxSpread && bidRate != 0 && askRate != 0;
return (validity_, kyberPrice_);
}
// INTERNAL FUNCTIONS
/// @dev Return Kyber ETH asset symbol if _asset is WETH
function __getKyberMaskAsset(address _asset) internal view returns (address) {
if (_asset == registry.nativeAsset()) {
return address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
}
return _asset;
}
/// @dev Get quantity of _baseAsset per whole _quoteAsset
/// @dev This function will not revert if there is no price, but return (false,0,0)
function __getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)
internal
view
returns (bool isValid_, uint256 referencePrice_, uint256 quoteDecimals_)
{
isValid_ = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);
quoteDecimals_ = ERC20WithFields(_quoteAsset).decimals();
if (prices[_quoteAsset] == 0) {
return (false, 0, 0); // return early and avoid revert
}
referencePrice_ = mul(
prices[_baseAsset],
10 ** uint256(quoteDecimals_)
) / prices[_quoteAsset];
return (isValid_, referencePrice_, quoteDecimals_);
}
/// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice
function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
} | /// @title Price Feed Template
/// @author Melonport AG <[email protected]>
/// @notice Routes external prices to smart contracts from Kyber | NatSpecSingleLine | __priceIsSane | function __priceIsSane(
uint256 _priceFromKyber,
uint256 _sanePrice
)
internal
view
returns (bool)
{
uint256 deviation;
if (_priceFromKyber >= _sanePrice) {
deviation = sub(_priceFromKyber, _sanePrice);
} else {
deviation = sub(_sanePrice, _priceFromKyber);
}
return mul(deviation, 10 ** uint256(KYBER_PRECISION)) / _sanePrice <= maxPriceDeviation;
}
| /// @dev Whether _priceFromKyber deviates no more than some % from _sanePrice | NatSpecSingleLine | v0.6.1+commit.e6f7d5a4 | GNU GPLv3 | ://bfb6637c40f216637aec4ae865b552cdfb7385f35abfdc8605b64dfc9d3e53a3 | {
"func_code_index": [
12958,
13428
]
} | 7,531 |
SMT | SMT.sol | 0x15c2f2ef00b2fc24461e56e26f1166d2cead7ac9 | Solidity | SMT | contract SMT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SMT";
name = "Smart Media Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ---------------------------------------------------------------------------- | LineComment | totalSupply | function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
| // ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | bzzr://49aa17702999083866488e0d273fb5c0143ec14c43f2e5447a2044ceca498cec | {
"func_code_index": [
929,
1048
]
} | 7,532 |
|
SMT | SMT.sol | 0x15c2f2ef00b2fc24461e56e26f1166d2cead7ac9 | Solidity | SMT | contract SMT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SMT";
name = "Smart Media Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ---------------------------------------------------------------------------- | LineComment | balanceOf | function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
| // ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | bzzr://49aa17702999083866488e0d273fb5c0143ec14c43f2e5447a2044ceca498cec | {
"func_code_index": [
1270,
1395
]
} | 7,533 |
|
SMT | SMT.sol | 0x15c2f2ef00b2fc24461e56e26f1166d2cead7ac9 | Solidity | SMT | contract SMT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SMT";
name = "Smart Media Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ---------------------------------------------------------------------------- | LineComment | transfer | function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | bzzr://49aa17702999083866488e0d273fb5c0143ec14c43f2e5447a2044ceca498cec | {
"func_code_index": [
1741,
2013
]
} | 7,534 |
|
SMT | SMT.sol | 0x15c2f2ef00b2fc24461e56e26f1166d2cead7ac9 | Solidity | SMT | contract SMT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SMT";
name = "Smart Media Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ---------------------------------------------------------------------------- | LineComment | approve | function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | bzzr://49aa17702999083866488e0d273fb5c0143ec14c43f2e5447a2044ceca498cec | {
"func_code_index": [
2524,
2737
]
} | 7,535 |
|
SMT | SMT.sol | 0x15c2f2ef00b2fc24461e56e26f1166d2cead7ac9 | Solidity | SMT | contract SMT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SMT";
name = "Smart Media Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ---------------------------------------------------------------------------- | LineComment | transferFrom | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | bzzr://49aa17702999083866488e0d273fb5c0143ec14c43f2e5447a2044ceca498cec | {
"func_code_index": [
3275,
3623
]
} | 7,536 |
|
SMT | SMT.sol | 0x15c2f2ef00b2fc24461e56e26f1166d2cead7ac9 | Solidity | SMT | contract SMT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SMT";
name = "Smart Media Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ---------------------------------------------------------------------------- | LineComment | allowance | function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
| // ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | bzzr://49aa17702999083866488e0d273fb5c0143ec14c43f2e5447a2044ceca498cec | {
"func_code_index": [
3906,
4058
]
} | 7,537 |
|
SMT | SMT.sol | 0x15c2f2ef00b2fc24461e56e26f1166d2cead7ac9 | Solidity | SMT | contract SMT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SMT";
name = "Smart Media Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ---------------------------------------------------------------------------- | LineComment | approveAndCall | function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | bzzr://49aa17702999083866488e0d273fb5c0143ec14c43f2e5447a2044ceca498cec | {
"func_code_index": [
4421,
4743
]
} | 7,538 |
|
SMT | SMT.sol | 0x15c2f2ef00b2fc24461e56e26f1166d2cead7ac9 | Solidity | SMT | contract SMT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SMT";
name = "Smart Media Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ---------------------------------------------------------------------------- | LineComment | function () public payable {
revert();
}
| // ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | bzzr://49aa17702999083866488e0d273fb5c0143ec14c43f2e5447a2044ceca498cec | {
"func_code_index": [
4935,
4994
]
} | 7,539 |
||
SMT | SMT.sol | 0x15c2f2ef00b2fc24461e56e26f1166d2cead7ac9 | Solidity | SMT | contract SMT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SMT";
name = "Smart Media Token";
decimals = 18;
_totalSupply = 100000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and a
// fixed supply
// ---------------------------------------------------------------------------- | LineComment | transferAnyERC20Token | function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
| // ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | bzzr://49aa17702999083866488e0d273fb5c0143ec14c43f2e5447a2044ceca498cec | {
"func_code_index": [
5227,
5416
]
} | 7,540 |
|
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
| /**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
815,
932
]
} | 7,541 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
1097,
1205
]
} | 7,542 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | _transferOwnership | function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
| /**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
1343,
1521
]
} | 7,543 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | SmartFundRegistry | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// address of platdorm wallet contract
address public COTDAOWallet;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStabelsInterface public permittedStabels;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _COTDAOWallet address of platform wallet contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStabels Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
*/
constructor(
address _COTDAOWallet,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStabels,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther
) public {
COTDAOWallet = _COTDAOWallet;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStabels = PermittedStabelsInterface(_permittedStabels);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | /*
* The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts
*/ | Comment | createSmartFund | function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
| /**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
3423,
4605
]
} | 7,544 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | SmartFundRegistry | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// address of platdorm wallet contract
address public COTDAOWallet;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStabelsInterface public permittedStabels;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _COTDAOWallet address of platform wallet contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStabels Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
*/
constructor(
address _COTDAOWallet,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStabels,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther
) public {
COTDAOWallet = _COTDAOWallet;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStabels = PermittedStabelsInterface(_permittedStabels);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | /*
* The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts
*/ | Comment | setExchangePortalAddress | function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
| /**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
5139,
5450
]
} | 7,545 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | SmartFundRegistry | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// address of platdorm wallet contract
address public COTDAOWallet;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStabelsInterface public permittedStabels;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _COTDAOWallet address of platform wallet contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStabels Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
*/
constructor(
address _COTDAOWallet,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStabels,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther
) public {
COTDAOWallet = _COTDAOWallet;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStabels = PermittedStabelsInterface(_permittedStabels);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | /*
* The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts
*/ | Comment | setPoolPortalAddress | function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
| /**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
5597,
5872
]
} | 7,546 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | SmartFundRegistry | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// address of platdorm wallet contract
address public COTDAOWallet;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStabelsInterface public permittedStabels;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _COTDAOWallet address of platform wallet contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStabels Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
*/
constructor(
address _COTDAOWallet,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStabels,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther
) public {
COTDAOWallet = _COTDAOWallet;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStabels = PermittedStabelsInterface(_permittedStabels);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | /*
* The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts
*/ | Comment | setMaximumSuccessFee | function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
| /**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
6019,
6150
]
} | 7,547 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | SmartFundRegistry | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// address of platdorm wallet contract
address public COTDAOWallet;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStabelsInterface public permittedStabels;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _COTDAOWallet address of platform wallet contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStabels Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
*/
constructor(
address _COTDAOWallet,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStabels,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther
) public {
COTDAOWallet = _COTDAOWallet;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStabels = PermittedStabelsInterface(_permittedStabels);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | /*
* The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts
*/ | Comment | setPlatformFee | function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
| /**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
6277,
6384
]
} | 7,548 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | SmartFundRegistry | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// address of platdorm wallet contract
address public COTDAOWallet;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStabelsInterface public permittedStabels;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _COTDAOWallet address of platform wallet contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStabels Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
*/
constructor(
address _COTDAOWallet,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStabels,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther
) public {
COTDAOWallet = _COTDAOWallet;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStabels = PermittedStabelsInterface(_permittedStabels);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | /*
* The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts
*/ | Comment | changeStableCoinAddress | function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
| /**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
6497,
6702
]
} | 7,549 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | SmartFundRegistry | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// address of platdorm wallet contract
address public COTDAOWallet;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStabelsInterface public permittedStabels;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _COTDAOWallet address of platform wallet contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStabels Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
*/
constructor(
address _COTDAOWallet,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStabels,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther
) public {
COTDAOWallet = _COTDAOWallet;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStabels = PermittedStabelsInterface(_permittedStabels);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | /*
* The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts
*/ | Comment | withdrawTokens | function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
| /**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
6871,
7040
]
} | 7,550 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | SmartFundRegistry | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// address of platdorm wallet contract
address public COTDAOWallet;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStabelsInterface public permittedStabels;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _COTDAOWallet address of platform wallet contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStabels Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
*/
constructor(
address _COTDAOWallet,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStabels,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther
) public {
COTDAOWallet = _COTDAOWallet;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStabels = PermittedStabelsInterface(_permittedStabels);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | /*
* The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts
*/ | Comment | withdrawEther | function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
| /**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
7137,
7234
]
} | 7,551 |
SmartFundRegistry | SmartFundRegistry.sol | 0xc8a6346133289ef7a7c104c1dc70e1da43a62cc6 | Solidity | SmartFundRegistry | contract SmartFundRegistry is Ownable {
address[] public smartFunds;
// address of platdorm wallet contract
address public COTDAOWallet;
// The Smart Contract which stores the addresses of all the authorized Exchange Portals
PermittedExchangesInterface public permittedExchanges;
// The Smart Contract which stores the addresses of all the authorized Pool Portals
PermittedPoolsInterface public permittedPools;
// The Smart Contract which stores the addresses of all the authorized stable coins
PermittedStabelsInterface public permittedStabels;
// Addresses of portals
address public poolPortalAddress;
address public exchangePortalAddress;
// platForm fee is out of 10,000, e.g 2500 is 25%
uint256 public platformFee;
// Default maximum success fee is 3000/30%
uint256 public maximumSuccessFee = 3000;
// Address of stable coin can be set in constructor and changed via function
address public stableCoinAddress;
// Addresses for Compound platform
address public cEther;
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory;
SmartFundUSDFactoryInterface public smartFundUSDFactory;
event SmartFundAdded(address indexed smartFundAddress, address indexed owner);
/**
* @dev contructor
*
* @param _COTDAOWallet address of platform wallet contract
* @param _platformFee Initial platform fee
* @param _permittedExchangesAddress Address of the permittedExchanges contract
* @param _exchangePortalAddress Address of the initial ExchangePortal contract
* @param _permittedPoolAddress Address of the permittedPool contract
* @param _poolPortalAddress Address of the initial PoolPortal contract
* @param _permittedStabels Address of the permittesStabels contract
* @param _stableCoinAddress Address of the stable coin
* @param _smartFundETHFactory Address of smartFund ETH factory
* @param _smartFundUSDFactory Address of smartFund USD factory
* @param _cEther Address of Compound ETH wrapper
*/
constructor(
address _COTDAOWallet,
uint256 _platformFee,
address _permittedExchangesAddress,
address _exchangePortalAddress,
address _permittedPoolAddress,
address _poolPortalAddress,
address _permittedStabels,
address _stableCoinAddress,
address _smartFundETHFactory,
address _smartFundUSDFactory,
address _cEther
) public {
COTDAOWallet = _COTDAOWallet;
platformFee = _platformFee;
exchangePortalAddress = _exchangePortalAddress;
permittedExchanges = PermittedExchangesInterface(_permittedExchangesAddress);
permittedPools = PermittedPoolsInterface(_permittedPoolAddress);
permittedStabels = PermittedStabelsInterface(_permittedStabels);
poolPortalAddress = _poolPortalAddress;
stableCoinAddress = _stableCoinAddress;
smartFundETHFactory = SmartFundETHFactoryInterface(_smartFundETHFactory);
smartFundUSDFactory = SmartFundUSDFactoryInterface(_smartFundUSDFactory);
cEther = _cEther;
}
/**
* @dev Creates a new SmartFund
*
* @param _name The name of the new fund
* @param _successFee The fund managers success fee
* @param _isStableBasedFund true for USD base fund, false for ETH base
*/
function createSmartFund(
string _name,
uint256 _successFee,
bool _isStableBasedFund
) public {
// Require that the funds success fee be less than the maximum allowed amount
require(_successFee <= maximumSuccessFee);
address owner = msg.sender;
address smartFund;
if(_isStableBasedFund){
// Create USD Fund
smartFund = smartFundUSDFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
address(permittedStabels),
poolPortalAddress,
stableCoinAddress,
cEther
);
}else{
// Create ETH Fund
smartFund = smartFundETHFactory.createSmartFund(
owner,
_name,
_successFee,
platformFee,
COTDAOWallet,
exchangePortalAddress,
address(permittedExchanges),
address(permittedPools),
poolPortalAddress,
cEther
);
}
smartFunds.push(smartFund);
emit SmartFundAdded(smartFund, owner);
}
function totalSmartFunds() public view returns (uint256) {
return smartFunds.length;
}
function getAllSmartFundAddresses() public view returns(address[]) {
address[] memory addresses = new address[](smartFunds.length);
for (uint i; i < smartFunds.length; i++) {
addresses[i] = address(smartFunds[i]);
}
return addresses;
}
/**
* @dev Sets a new default ExchangePortal address
*
* @param _newExchangePortalAddress Address of the new exchange portal to be set
*/
function setExchangePortalAddress(address _newExchangePortalAddress) public onlyOwner {
// Require that the new exchange portal is permitted by permittedExchanges
require(permittedExchanges.permittedAddresses(_newExchangePortalAddress));
exchangePortalAddress = _newExchangePortalAddress;
}
/**
* @dev Sets a new default Portal Portal address
*
* @param _poolPortalAddress Address of the new pool portal to be set
*/
function setPoolPortalAddress (address _poolPortalAddress) external onlyOwner {
// Require that the new pool portal is permitted by permittedPools
require(permittedPools.permittedAddresses(_poolPortalAddress));
poolPortalAddress = _poolPortalAddress;
}
/**
* @dev Sets maximum success fee for all newly created SmartFunds
*
* @param _maximumSuccessFee New maximum success fee
*/
function setMaximumSuccessFee(uint256 _maximumSuccessFee) external onlyOwner {
maximumSuccessFee = _maximumSuccessFee;
}
/**
* @dev Sets platform fee for all newly created SmartFunds
*
* @param _platformFee New platform fee
*/
function setPlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
}
/**
* @dev Sets new stableCoinAddress
*
* @param _stableCoinAddress New stable address
*/
function changeStableCoinAddress(address _stableCoinAddress) external onlyOwner {
require(permittedStabels.permittedAddresses(_stableCoinAddress));
stableCoinAddress = _stableCoinAddress;
}
/**
* @dev Allows platform to withdraw tokens received as part of the platform fee
*
* @param _tokenAddress Address of the token to be withdrawn
*/
function withdrawTokens(address _tokenAddress) external onlyOwner {
ERC20 token = ERC20(_tokenAddress);
token.transfer(owner, token.balanceOf(this));
}
/**
* @dev Allows platform to withdraw ether received as part of the platform fee
*/
function withdrawEther() external onlyOwner {
owner.transfer(address(this).balance);
}
// Fallback payable function in order to receive ether when fund manager withdraws their cut
function() public payable {}
} | /*
* The SmartFundRegistry is used to manage the creation and permissions of SmartFund contracts
*/ | Comment | function() public payable {}
| // Fallback payable function in order to receive ether when fund manager withdraws their cut | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://613e35e15ecb998f7c9c1ab6758f77e374d35c73c40bb1dbf0218a31293babda | {
"func_code_index": [
7333,
7364
]
} | 7,552 |
|
ParamBook | ParamBook.sol | 0xbc91c117157d7c47135b13c97ec4a46fa1ca1ab1 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @dev 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 returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://aaec16ae5de700b97a777e545f12053b8958b5e4085955a6272b1ba07b897c5c | {
"func_code_index": [
497,
581
]
} | 7,553 |
ParamBook | ParamBook.sol | 0xbc91c117157d7c47135b13c97ec4a46fa1ca1ab1 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @dev 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 | MIT | ipfs://aaec16ae5de700b97a777e545f12053b8958b5e4085955a6272b1ba07b897c5c | {
"func_code_index": [
1139,
1292
]
} | 7,554 |
ParamBook | ParamBook.sol | 0xbc91c117157d7c47135b13c97ec4a46fa1ca1ab1 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @dev 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 | MIT | ipfs://aaec16ae5de700b97a777e545f12053b8958b5e4085955a6272b1ba07b897c5c | {
"func_code_index": [
1442,
1691
]
} | 7,555 |
AccessChain | AccessChain.sol | 0xcaf5d1ad6e64e5968d3140551c14dcdff28c3a3b | Solidity | AccessChain | contract AccessChain is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASIC";
name = "AccessChain";
decimals = 18;
_totalSupply = 12000000000000000000000000;
balances[0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a] = _totalSupply;
emit Transfer(address(0), 0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | totalSupply | function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
| // ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------ | LineComment | v0.4.26+commit.4563c3fc | None | bzzr://2b411a5cd96a7f8beb1b67fca4b5d14053725a17a9f4b09d2c85d5d36e836f53 | {
"func_code_index": [
985,
1106
]
} | 7,556 |
AccessChain | AccessChain.sol | 0xcaf5d1ad6e64e5968d3140551c14dcdff28c3a3b | Solidity | AccessChain | contract AccessChain is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASIC";
name = "AccessChain";
decimals = 18;
_totalSupply = 12000000000000000000000000;
balances[0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a] = _totalSupply;
emit Transfer(address(0), 0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | balanceOf | function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
| // ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------ | LineComment | v0.4.26+commit.4563c3fc | None | bzzr://2b411a5cd96a7f8beb1b67fca4b5d14053725a17a9f4b09d2c85d5d36e836f53 | {
"func_code_index": [
1326,
1455
]
} | 7,557 |
AccessChain | AccessChain.sol | 0xcaf5d1ad6e64e5968d3140551c14dcdff28c3a3b | Solidity | AccessChain | contract AccessChain is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASIC";
name = "AccessChain";
decimals = 18;
_totalSupply = 12000000000000000000000000;
balances[0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a] = _totalSupply;
emit Transfer(address(0), 0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transfer | function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.26+commit.4563c3fc | None | bzzr://2b411a5cd96a7f8beb1b67fca4b5d14053725a17a9f4b09d2c85d5d36e836f53 | {
"func_code_index": [
1799,
2081
]
} | 7,558 |
AccessChain | AccessChain.sol | 0xcaf5d1ad6e64e5968d3140551c14dcdff28c3a3b | Solidity | AccessChain | contract AccessChain is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASIC";
name = "AccessChain";
decimals = 18;
_totalSupply = 12000000000000000000000000;
balances[0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a] = _totalSupply;
emit Transfer(address(0), 0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | approve | function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------ | LineComment | v0.4.26+commit.4563c3fc | None | bzzr://2b411a5cd96a7f8beb1b67fca4b5d14053725a17a9f4b09d2c85d5d36e836f53 | {
"func_code_index": [
2589,
2802
]
} | 7,559 |
AccessChain | AccessChain.sol | 0xcaf5d1ad6e64e5968d3140551c14dcdff28c3a3b | Solidity | AccessChain | contract AccessChain is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASIC";
name = "AccessChain";
decimals = 18;
_totalSupply = 12000000000000000000000000;
balances[0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a] = _totalSupply;
emit Transfer(address(0), 0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transferFrom | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.26+commit.4563c3fc | None | bzzr://2b411a5cd96a7f8beb1b67fca4b5d14053725a17a9f4b09d2c85d5d36e836f53 | {
"func_code_index": [
3333,
3696
]
} | 7,560 |
AccessChain | AccessChain.sol | 0xcaf5d1ad6e64e5968d3140551c14dcdff28c3a3b | Solidity | AccessChain | contract AccessChain is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASIC";
name = "AccessChain";
decimals = 18;
_totalSupply = 12000000000000000000000000;
balances[0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a] = _totalSupply;
emit Transfer(address(0), 0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | allowance | function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
| // ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------ | LineComment | v0.4.26+commit.4563c3fc | None | bzzr://2b411a5cd96a7f8beb1b67fca4b5d14053725a17a9f4b09d2c85d5d36e836f53 | {
"func_code_index": [
3979,
4135
]
} | 7,561 |
AccessChain | AccessChain.sol | 0xcaf5d1ad6e64e5968d3140551c14dcdff28c3a3b | Solidity | AccessChain | contract AccessChain is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASIC";
name = "AccessChain";
decimals = 18;
_totalSupply = 12000000000000000000000000;
balances[0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a] = _totalSupply;
emit Transfer(address(0), 0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | approveAndCall | function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------ | LineComment | v0.4.26+commit.4563c3fc | None | bzzr://2b411a5cd96a7f8beb1b67fca4b5d14053725a17a9f4b09d2c85d5d36e836f53 | {
"func_code_index": [
4490,
4812
]
} | 7,562 |
AccessChain | AccessChain.sol | 0xcaf5d1ad6e64e5968d3140551c14dcdff28c3a3b | Solidity | AccessChain | contract AccessChain is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASIC";
name = "AccessChain";
decimals = 18;
_totalSupply = 12000000000000000000000000;
balances[0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a] = _totalSupply;
emit Transfer(address(0), 0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | function () public payable {
revert();
}
| // ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------ | LineComment | v0.4.26+commit.4563c3fc | None | bzzr://2b411a5cd96a7f8beb1b67fca4b5d14053725a17a9f4b09d2c85d5d36e836f53 | {
"func_code_index": [
5004,
5063
]
} | 7,563 |
|
AccessChain | AccessChain.sol | 0xcaf5d1ad6e64e5968d3140551c14dcdff28c3a3b | Solidity | AccessChain | contract AccessChain is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ASIC";
name = "AccessChain";
decimals = 18;
_totalSupply = 12000000000000000000000000;
balances[0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a] = _totalSupply;
emit Transfer(address(0), 0xBEAA4020F8346fbDB503b17C0f5EfCDbBae95A6a, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transferAnyERC20Token | function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
| // ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------ | LineComment | v0.4.26+commit.4563c3fc | None | bzzr://2b411a5cd96a7f8beb1b67fca4b5d14053725a17a9f4b09d2c85d5d36e836f53 | {
"func_code_index": [
5296,
5485
]
} | 7,564 |
ARKToken | ARKToken.sol | 0x30bca884fb83165ce17bde655552596fe5c59c5d | Solidity | ARKToken | contract ARKToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ARK";
name = "ARKToken";
decimals = 15;
_totalSupply = 10000000000000000000000;
balances[0x12BdBd520DE427b84Aec2851fd571a139C706e46] = _totalSupply;
emit Transfer(address(0), 0x12BdBd520DE427b84Aec2851fd571a139C706e46, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | totalSupply | function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
| // ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://af6879d1bdf636e3b8b12381aa2866bfe984b0d5a680df0d75d6abeffccdea26 | {
"func_code_index": [
975,
1096
]
} | 7,565 |
||
ARKToken | ARKToken.sol | 0x30bca884fb83165ce17bde655552596fe5c59c5d | Solidity | ARKToken | contract ARKToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ARK";
name = "ARKToken";
decimals = 15;
_totalSupply = 10000000000000000000000;
balances[0x12BdBd520DE427b84Aec2851fd571a139C706e46] = _totalSupply;
emit Transfer(address(0), 0x12BdBd520DE427b84Aec2851fd571a139C706e46, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | balanceOf | function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
| // ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://af6879d1bdf636e3b8b12381aa2866bfe984b0d5a680df0d75d6abeffccdea26 | {
"func_code_index": [
1316,
1445
]
} | 7,566 |
||
ARKToken | ARKToken.sol | 0x30bca884fb83165ce17bde655552596fe5c59c5d | Solidity | ARKToken | contract ARKToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ARK";
name = "ARKToken";
decimals = 15;
_totalSupply = 10000000000000000000000;
balances[0x12BdBd520DE427b84Aec2851fd571a139C706e46] = _totalSupply;
emit Transfer(address(0), 0x12BdBd520DE427b84Aec2851fd571a139C706e46, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | transfer | function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://af6879d1bdf636e3b8b12381aa2866bfe984b0d5a680df0d75d6abeffccdea26 | {
"func_code_index": [
1789,
2071
]
} | 7,567 |
||
ARKToken | ARKToken.sol | 0x30bca884fb83165ce17bde655552596fe5c59c5d | Solidity | ARKToken | contract ARKToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ARK";
name = "ARKToken";
decimals = 15;
_totalSupply = 10000000000000000000000;
balances[0x12BdBd520DE427b84Aec2851fd571a139C706e46] = _totalSupply;
emit Transfer(address(0), 0x12BdBd520DE427b84Aec2851fd571a139C706e46, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | approve | function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| // ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://af6879d1bdf636e3b8b12381aa2866bfe984b0d5a680df0d75d6abeffccdea26 | {
"func_code_index": [
2163,
2376
]
} | 7,568 |
||
ARKToken | ARKToken.sol | 0x30bca884fb83165ce17bde655552596fe5c59c5d | Solidity | ARKToken | contract ARKToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ARK";
name = "ARKToken";
decimals = 15;
_totalSupply = 10000000000000000000000;
balances[0x12BdBd520DE427b84Aec2851fd571a139C706e46] = _totalSupply;
emit Transfer(address(0), 0x12BdBd520DE427b84Aec2851fd571a139C706e46, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | transferFrom | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://af6879d1bdf636e3b8b12381aa2866bfe984b0d5a680df0d75d6abeffccdea26 | {
"func_code_index": [
2906,
3269
]
} | 7,569 |
||
ARKToken | ARKToken.sol | 0x30bca884fb83165ce17bde655552596fe5c59c5d | Solidity | ARKToken | contract ARKToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ARK";
name = "ARKToken";
decimals = 15;
_totalSupply = 10000000000000000000000;
balances[0x12BdBd520DE427b84Aec2851fd571a139C706e46] = _totalSupply;
emit Transfer(address(0), 0x12BdBd520DE427b84Aec2851fd571a139C706e46, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | allowance | function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
| // ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://af6879d1bdf636e3b8b12381aa2866bfe984b0d5a680df0d75d6abeffccdea26 | {
"func_code_index": [
3552,
3708
]
} | 7,570 |
||
ARKToken | ARKToken.sol | 0x30bca884fb83165ce17bde655552596fe5c59c5d | Solidity | ARKToken | contract ARKToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ARK";
name = "ARKToken";
decimals = 15;
_totalSupply = 10000000000000000000000;
balances[0x12BdBd520DE427b84Aec2851fd571a139C706e46] = _totalSupply;
emit Transfer(address(0), 0x12BdBd520DE427b84Aec2851fd571a139C706e46, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | approveAndCall | function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://af6879d1bdf636e3b8b12381aa2866bfe984b0d5a680df0d75d6abeffccdea26 | {
"func_code_index": [
4063,
4385
]
} | 7,571 |
||
ARKToken | ARKToken.sol | 0x30bca884fb83165ce17bde655552596fe5c59c5d | Solidity | ARKToken | contract ARKToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "ARK";
name = "ARKToken";
decimals = 15;
_totalSupply = 10000000000000000000000;
balances[0x12BdBd520DE427b84Aec2851fd571a139C706e46] = _totalSupply;
emit Transfer(address(0), 0x12BdBd520DE427b84Aec2851fd571a139C706e46, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | function () public payable {
revert();
}
| // ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://af6879d1bdf636e3b8b12381aa2866bfe984b0d5a680df0d75d6abeffccdea26 | {
"func_code_index": [
4577,
4636
]
} | 7,572 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | buy | function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
| /**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
10404,
10532
]
} | 7,573 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | function()
payable
public
{
purchaseTokens(msg.value);
}
| /**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
10702,
10800
]
} | 7,574 |
||||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | reinvest | function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
| /**
* Converts all of caller's dividends to tokens.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
10875,
11327
]
} | 7,575 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | exit | function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
| /**
* Alias of sell(), acquireDividends() and withdraw().
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
11408,
11824
]
} | 7,576 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | acquireDividends | function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
| /**
* Withdraws all of the caller's dividends in previous round.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
11912,
12683
]
} | 7,577 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | withdraw | function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
| /**
* Withdraws all of the caller's income.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
12750,
13163
]
} | 7,578 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | taxDividends | function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
| /**
* Tax dividends to community.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
13219,
13672
]
} | 7,579 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | sell | function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
| /**
* Liquifies tokens to ethereum.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
13731,
15558
]
} | 7,580 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | transfer | function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
| /**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
15688,
17181
]
} | 7,581 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | disableInitialStage | function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
| /**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
17373,
17501
]
} | 7,582 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | setAdministrator | function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
| /**
* In case one of us dies, we need to replace ourselves.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
17584,
17756
]
} | 7,583 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | setName | function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
| /**
* If we want to rebrand, we can.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
17816,
17933
]
} | 7,584 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | setSymbol | function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
| /**
* If we want to rebrand, we can.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
17993,
18118
]
} | 7,585 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | activate | function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
| /**
Start this game.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
18162,
18560
]
} | 7,586 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | totalEthereumBalance | function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
| /**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
18745,
18887
]
} | 7,587 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | totalSupply | function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
| /**
* Retrieve the total token supply.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
18949,
19076
]
} | 7,588 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | myTokens | function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
| /**
* Retrieve the tokens owned by the caller.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
19146,
19333
]
} | 7,589 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | myDividends | function myDividends(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
| /**
* 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.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
19684,
19848
]
} | 7,590 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | balanceOf | function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
| /**
* Retrieve the token balance of any single address.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
19927,
20101
]
} | 7,591 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | dividendsOf | function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
| /**
* Retrieve the dividend balance of any single address.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
20183,
20804
]
} | 7,592 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | estimateDividends | function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
| /**
* Estimate user dividends in current round.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
20874,
21403
]
} | 7,593 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | 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(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
| /**
* Return the buy price of 1 individual token.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
21476,
22021
]
} | 7,594 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | 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);
return _ethereum;
}
}
| /**
* Return the sell price of 1 individual token.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
22095,
22484
]
} | 7,595 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | calculateTokensReceived | function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
| /**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
22596,
22834
]
} | 7,596 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | calculateEthereumReceived | function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
| /**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
22947,
23363
]
} | 7,597 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | purchaseTokens | function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
| /*==========================================
= INTERNAL FUNCTIONS =
==========================================*/ | Comment | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
25404,
27501
]
} | 7,598 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | 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;
}
| /**
* 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.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
27792,
28770
]
} | 7,599 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | 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;
| /**
* 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.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
29027,
29755
]
} | 7,600 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | withdrawComm1 | function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
| /*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/ | Comment | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
29908,
30181
]
} | 7,601 |
|||
RunAway | RunAway.sol | 0x692b856117039d424cfac420f93ab2451f3c9eb5 | Solidity | RunAway | contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
/**
* @dev prevents contracts from interacting with me
*/
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> start the game(activate)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
/*=====================================
= Structs =
=====================================*/
struct Round {
uint256 roundID; // Starting from 1, increasing by 1
uint256 netBuySum; // Sum of all userNetBuy which are > 0
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
// Rounds recorder
mapping(uint256=>Round) public rounds_;
// Fees storage accounts
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
// Current round ID
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
// Is game started?
bool public activated_=false;
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
// Income, including dividends in each round and sale income.
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
// add the ambassadors here.
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
//clear income of this user
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
// fire event
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
/**
* Alias of sell(), acquireDividends() and withdraw().
*/
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the caller's dividends in previous round.
*/
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
// setup data
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID); // get ref. bonus later in the code
// update dividend tracker
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
// Add dividends to income.
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
// fire event
emit onAcquireDividends(_customerAddress, _dividends);
}
/**
* Withdraws all of the caller's income.
*/
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
//clear value
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
// fire event
emit onWithdraw(_customerAddress, myIncome);
}
/**
* Tax dividends to community.
*/
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
// Taxed dividends
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
// Community fees
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// Record income
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
// burn the sold tokens
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
// Calculate net buy of current round
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// Taxed dividends
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
// burn the fee tokens
tokenSupply_ = tokenSupply_.sub(_tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
Start this game.
*/
function activate()
onlyAdministrator()
public
{
// can only be ran once
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* 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(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
/**
* Estimate user dividends in current round.
*/
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
// Sold >= bought
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
// Nobody sold.
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
/**
* 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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
// data setup
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
// 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 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
/**
* 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;
}
/**
* 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;
}
/*==========================================
= COMMUNITY FUNCTIONS =
==========================================*/
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
} | sqrt | function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
| //This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://2db0ef42fe14458f087a43ebbcd18ee837535c8916ef75dd7f0fe57160a786c5 | {
"func_code_index": [
31254,
31457
]
} | 7,602 |
|||
UniV3PairManagerFactory | solidity/contracts/UniV3PairManager.sol | 0x005634cfef45e5a19c84aede6f0af17833471852 | Solidity | UniV3PairManager | contract UniV3PairManager is IUniV3PairManager, Governable {
/// @inheritdoc IERC20Metadata
string public override name;
/// @inheritdoc IERC20Metadata
string public override symbol;
/// @inheritdoc IERC20
uint256 public override totalSupply = 0;
/// @inheritdoc IPairManager
address public immutable override token0;
/// @inheritdoc IPairManager
address public immutable override token1;
/// @inheritdoc IPairManager
address public immutable override pool;
/// @inheritdoc IUniV3PairManager
uint24 public immutable override fee;
/// @inheritdoc IUniV3PairManager
uint160 public immutable override sqrtRatioAX96;
/// @inheritdoc IUniV3PairManager
uint160 public immutable override sqrtRatioBX96;
/// @notice Lowest possible tick in the Uniswap's curve
int24 private constant _TICK_LOWER = -887200;
/// @notice Highest possible tick in the Uniswap's curve
int24 private constant _TICK_UPPER = 887200;
/// @inheritdoc IERC20Metadata
//solhint-disable-next-line const-name-snakecase
uint8 public constant override decimals = 18;
/// @inheritdoc IERC20
mapping(address => mapping(address => uint256)) public override allowance;
/// @inheritdoc IERC20
mapping(address => uint256) public override balanceOf;
/// @notice Struct that contains token0, token1, and fee of the Uniswap pool
PoolAddress.PoolKey private _poolKey;
constructor(address _pool, address _governance) Governable(_governance) {
pool = _pool;
uint24 _fee = IUniswapV3Pool(_pool).fee();
fee = _fee;
address _token0 = IUniswapV3Pool(_pool).token0();
address _token1 = IUniswapV3Pool(_pool).token1();
token0 = _token0;
token1 = _token1;
name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol()));
symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol()));
sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER);
sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER);
_poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee});
}
// This low-level function should be called from a contract which performs important safety checks
/// @inheritdoc IUniV3PairManager
function mint(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint128 liquidity) {
(liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min);
_mint(to, liquidity);
}
/// @inheritdoc IUniV3PairManager
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external override {
MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
if (msg.sender != pool) revert OnlyPool();
if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed);
if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed);
}
/// @inheritdoc IUniV3PairManager
function burn(
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity);
if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage();
IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1));
_burn(msg.sender, liquidity);
}
/// @inheritdoc IUniV3PairManager
function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) {
(, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions(
keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER))
);
(amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1);
}
/// @inheritdoc IUniV3PairManager
function position()
external
view
override
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions(
keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER))
);
}
/// @inheritdoc IERC20
function approve(address spender, uint256 amount) external override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @inheritdoc IERC20
function transfer(address to, uint256 amount) external override returns (bool) {
_transferTokens(msg.sender, to, amount);
return true;
}
/// @inheritdoc IERC20
function transferFrom(
address from,
address to,
uint256 amount
) external override returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = allowance[from][spender];
if (spender != from && spenderAllowance != type(uint256).max) {
uint256 newAllowance = spenderAllowance - amount;
allowance[from][spender] = newAllowance;
emit Approval(from, spender, newAllowance);
}
_transferTokens(from, to, amount);
return true;
}
/// @notice Adds liquidity to an initialized pool
/// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min
/// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback
/// @param amount0Desired The amount of token0 we would like to provide
/// @param amount1Desired The amount of token1 we would like to provide
/// @param amount0Min The minimum amount of token0 we want to provide
/// @param amount1Min The minimum amount of token1 we want to provide
/// @return liquidity The calculated liquidity we get for the token amounts we provided
/// @return amount0 The amount of token0 we ended up providing
/// @return amount1 The amount of token1 we ended up providing
function _addLiquidity(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min
)
internal
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired);
(amount0, amount1) = IUniswapV3Pool(pool).mint(
address(this),
_TICK_LOWER,
_TICK_UPPER,
liquidity,
abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender}))
);
if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage();
}
/// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value
/// @param token The token to be transferred to the recipient
/// @param from The address of the payer
/// @param to The address of the passed-in tokens recipient
/// @param value How much of that token to be transferred from payer to the recipient
function _pay(
address token,
address from,
address to,
uint256 value
) internal {
_safeTransferFrom(token, from, to, value);
}
/// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount
/// @param to The recipient of the Keep3r credits
/// @param amount The amount Keep3r credits to be minted to the recipient
function _mint(address to, uint256 amount) internal {
totalSupply += amount;
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
/// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount
/// @param to The address that will get its Keep3r credits burned
/// @param amount The amount Keep3r credits to be burned from the recipient/recipient
function _burn(address to, uint256 amount) internal {
totalSupply -= amount;
balanceOf[to] -= amount;
emit Transfer(to, address(0), amount);
}
/// @notice Transfers amount of Keep3r credits between two addresses
/// @param from The user that transfers the Keep3r credits
/// @param to The user that receives the Keep3r credits
/// @param amount The amount of Keep3r credits to be transferred
function _transferTokens(
address from,
address to,
uint256 amount
) internal {
balanceOf[from] -= amount;
balanceOf[to] += amount;
emit Transfer(from, to, amount);
}
/// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value
/// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful,
/// or if the passed data length is different than 0 and the decoded data is not a boolean
/// @param token The token to be transferred to the specified "to"
/// @param from The address which is going to transfer the tokens
/// @param value How much of that token to be transferred from "from" to "to"
function _safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer();
}
} | mint | function mint(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint128 liquidity) {
(liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min);
_mint(to, liquidity);
}
| /// @inheritdoc IUniV3PairManager | NatSpecSingleLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
2261,
2571
]
} | 7,603 |
||||
UniV3PairManagerFactory | solidity/contracts/UniV3PairManager.sol | 0x005634cfef45e5a19c84aede6f0af17833471852 | Solidity | UniV3PairManager | contract UniV3PairManager is IUniV3PairManager, Governable {
/// @inheritdoc IERC20Metadata
string public override name;
/// @inheritdoc IERC20Metadata
string public override symbol;
/// @inheritdoc IERC20
uint256 public override totalSupply = 0;
/// @inheritdoc IPairManager
address public immutable override token0;
/// @inheritdoc IPairManager
address public immutable override token1;
/// @inheritdoc IPairManager
address public immutable override pool;
/// @inheritdoc IUniV3PairManager
uint24 public immutable override fee;
/// @inheritdoc IUniV3PairManager
uint160 public immutable override sqrtRatioAX96;
/// @inheritdoc IUniV3PairManager
uint160 public immutable override sqrtRatioBX96;
/// @notice Lowest possible tick in the Uniswap's curve
int24 private constant _TICK_LOWER = -887200;
/// @notice Highest possible tick in the Uniswap's curve
int24 private constant _TICK_UPPER = 887200;
/// @inheritdoc IERC20Metadata
//solhint-disable-next-line const-name-snakecase
uint8 public constant override decimals = 18;
/// @inheritdoc IERC20
mapping(address => mapping(address => uint256)) public override allowance;
/// @inheritdoc IERC20
mapping(address => uint256) public override balanceOf;
/// @notice Struct that contains token0, token1, and fee of the Uniswap pool
PoolAddress.PoolKey private _poolKey;
constructor(address _pool, address _governance) Governable(_governance) {
pool = _pool;
uint24 _fee = IUniswapV3Pool(_pool).fee();
fee = _fee;
address _token0 = IUniswapV3Pool(_pool).token0();
address _token1 = IUniswapV3Pool(_pool).token1();
token0 = _token0;
token1 = _token1;
name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol()));
symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol()));
sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER);
sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER);
_poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee});
}
// This low-level function should be called from a contract which performs important safety checks
/// @inheritdoc IUniV3PairManager
function mint(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint128 liquidity) {
(liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min);
_mint(to, liquidity);
}
/// @inheritdoc IUniV3PairManager
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external override {
MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
if (msg.sender != pool) revert OnlyPool();
if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed);
if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed);
}
/// @inheritdoc IUniV3PairManager
function burn(
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity);
if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage();
IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1));
_burn(msg.sender, liquidity);
}
/// @inheritdoc IUniV3PairManager
function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) {
(, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions(
keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER))
);
(amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1);
}
/// @inheritdoc IUniV3PairManager
function position()
external
view
override
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions(
keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER))
);
}
/// @inheritdoc IERC20
function approve(address spender, uint256 amount) external override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @inheritdoc IERC20
function transfer(address to, uint256 amount) external override returns (bool) {
_transferTokens(msg.sender, to, amount);
return true;
}
/// @inheritdoc IERC20
function transferFrom(
address from,
address to,
uint256 amount
) external override returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = allowance[from][spender];
if (spender != from && spenderAllowance != type(uint256).max) {
uint256 newAllowance = spenderAllowance - amount;
allowance[from][spender] = newAllowance;
emit Approval(from, spender, newAllowance);
}
_transferTokens(from, to, amount);
return true;
}
/// @notice Adds liquidity to an initialized pool
/// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min
/// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback
/// @param amount0Desired The amount of token0 we would like to provide
/// @param amount1Desired The amount of token1 we would like to provide
/// @param amount0Min The minimum amount of token0 we want to provide
/// @param amount1Min The minimum amount of token1 we want to provide
/// @return liquidity The calculated liquidity we get for the token amounts we provided
/// @return amount0 The amount of token0 we ended up providing
/// @return amount1 The amount of token1 we ended up providing
function _addLiquidity(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min
)
internal
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired);
(amount0, amount1) = IUniswapV3Pool(pool).mint(
address(this),
_TICK_LOWER,
_TICK_UPPER,
liquidity,
abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender}))
);
if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage();
}
/// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value
/// @param token The token to be transferred to the recipient
/// @param from The address of the payer
/// @param to The address of the passed-in tokens recipient
/// @param value How much of that token to be transferred from payer to the recipient
function _pay(
address token,
address from,
address to,
uint256 value
) internal {
_safeTransferFrom(token, from, to, value);
}
/// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount
/// @param to The recipient of the Keep3r credits
/// @param amount The amount Keep3r credits to be minted to the recipient
function _mint(address to, uint256 amount) internal {
totalSupply += amount;
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
/// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount
/// @param to The address that will get its Keep3r credits burned
/// @param amount The amount Keep3r credits to be burned from the recipient/recipient
function _burn(address to, uint256 amount) internal {
totalSupply -= amount;
balanceOf[to] -= amount;
emit Transfer(to, address(0), amount);
}
/// @notice Transfers amount of Keep3r credits between two addresses
/// @param from The user that transfers the Keep3r credits
/// @param to The user that receives the Keep3r credits
/// @param amount The amount of Keep3r credits to be transferred
function _transferTokens(
address from,
address to,
uint256 amount
) internal {
balanceOf[from] -= amount;
balanceOf[to] += amount;
emit Transfer(from, to, amount);
}
/// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value
/// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful,
/// or if the passed data length is different than 0 and the decoded data is not a boolean
/// @param token The token to be transferred to the specified "to"
/// @param from The address which is going to transfer the tokens
/// @param value How much of that token to be transferred from "from" to "to"
function _safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer();
}
} | uniswapV3MintCallback | function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external override {
MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
if (msg.sender != pool) revert OnlyPool();
if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed);
if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed);
}
| /// @inheritdoc IUniV3PairManager | NatSpecSingleLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
2609,
3047
]
} | 7,604 |
||||
UniV3PairManagerFactory | solidity/contracts/UniV3PairManager.sol | 0x005634cfef45e5a19c84aede6f0af17833471852 | Solidity | UniV3PairManager | contract UniV3PairManager is IUniV3PairManager, Governable {
/// @inheritdoc IERC20Metadata
string public override name;
/// @inheritdoc IERC20Metadata
string public override symbol;
/// @inheritdoc IERC20
uint256 public override totalSupply = 0;
/// @inheritdoc IPairManager
address public immutable override token0;
/// @inheritdoc IPairManager
address public immutable override token1;
/// @inheritdoc IPairManager
address public immutable override pool;
/// @inheritdoc IUniV3PairManager
uint24 public immutable override fee;
/// @inheritdoc IUniV3PairManager
uint160 public immutable override sqrtRatioAX96;
/// @inheritdoc IUniV3PairManager
uint160 public immutable override sqrtRatioBX96;
/// @notice Lowest possible tick in the Uniswap's curve
int24 private constant _TICK_LOWER = -887200;
/// @notice Highest possible tick in the Uniswap's curve
int24 private constant _TICK_UPPER = 887200;
/// @inheritdoc IERC20Metadata
//solhint-disable-next-line const-name-snakecase
uint8 public constant override decimals = 18;
/// @inheritdoc IERC20
mapping(address => mapping(address => uint256)) public override allowance;
/// @inheritdoc IERC20
mapping(address => uint256) public override balanceOf;
/// @notice Struct that contains token0, token1, and fee of the Uniswap pool
PoolAddress.PoolKey private _poolKey;
constructor(address _pool, address _governance) Governable(_governance) {
pool = _pool;
uint24 _fee = IUniswapV3Pool(_pool).fee();
fee = _fee;
address _token0 = IUniswapV3Pool(_pool).token0();
address _token1 = IUniswapV3Pool(_pool).token1();
token0 = _token0;
token1 = _token1;
name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol()));
symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol()));
sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER);
sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER);
_poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee});
}
// This low-level function should be called from a contract which performs important safety checks
/// @inheritdoc IUniV3PairManager
function mint(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint128 liquidity) {
(liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min);
_mint(to, liquidity);
}
/// @inheritdoc IUniV3PairManager
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external override {
MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
if (msg.sender != pool) revert OnlyPool();
if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed);
if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed);
}
/// @inheritdoc IUniV3PairManager
function burn(
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity);
if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage();
IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1));
_burn(msg.sender, liquidity);
}
/// @inheritdoc IUniV3PairManager
function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) {
(, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions(
keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER))
);
(amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1);
}
/// @inheritdoc IUniV3PairManager
function position()
external
view
override
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions(
keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER))
);
}
/// @inheritdoc IERC20
function approve(address spender, uint256 amount) external override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @inheritdoc IERC20
function transfer(address to, uint256 amount) external override returns (bool) {
_transferTokens(msg.sender, to, amount);
return true;
}
/// @inheritdoc IERC20
function transferFrom(
address from,
address to,
uint256 amount
) external override returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = allowance[from][spender];
if (spender != from && spenderAllowance != type(uint256).max) {
uint256 newAllowance = spenderAllowance - amount;
allowance[from][spender] = newAllowance;
emit Approval(from, spender, newAllowance);
}
_transferTokens(from, to, amount);
return true;
}
/// @notice Adds liquidity to an initialized pool
/// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min
/// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback
/// @param amount0Desired The amount of token0 we would like to provide
/// @param amount1Desired The amount of token1 we would like to provide
/// @param amount0Min The minimum amount of token0 we want to provide
/// @param amount1Min The minimum amount of token1 we want to provide
/// @return liquidity The calculated liquidity we get for the token amounts we provided
/// @return amount0 The amount of token0 we ended up providing
/// @return amount1 The amount of token1 we ended up providing
function _addLiquidity(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min
)
internal
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired);
(amount0, amount1) = IUniswapV3Pool(pool).mint(
address(this),
_TICK_LOWER,
_TICK_UPPER,
liquidity,
abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender}))
);
if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage();
}
/// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value
/// @param token The token to be transferred to the recipient
/// @param from The address of the payer
/// @param to The address of the passed-in tokens recipient
/// @param value How much of that token to be transferred from payer to the recipient
function _pay(
address token,
address from,
address to,
uint256 value
) internal {
_safeTransferFrom(token, from, to, value);
}
/// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount
/// @param to The recipient of the Keep3r credits
/// @param amount The amount Keep3r credits to be minted to the recipient
function _mint(address to, uint256 amount) internal {
totalSupply += amount;
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
/// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount
/// @param to The address that will get its Keep3r credits burned
/// @param amount The amount Keep3r credits to be burned from the recipient/recipient
function _burn(address to, uint256 amount) internal {
totalSupply -= amount;
balanceOf[to] -= amount;
emit Transfer(to, address(0), amount);
}
/// @notice Transfers amount of Keep3r credits between two addresses
/// @param from The user that transfers the Keep3r credits
/// @param to The user that receives the Keep3r credits
/// @param amount The amount of Keep3r credits to be transferred
function _transferTokens(
address from,
address to,
uint256 amount
) internal {
balanceOf[from] -= amount;
balanceOf[to] += amount;
emit Transfer(from, to, amount);
}
/// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value
/// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful,
/// or if the passed data length is different than 0 and the decoded data is not a boolean
/// @param token The token to be transferred to the specified "to"
/// @param from The address which is going to transfer the tokens
/// @param value How much of that token to be transferred from "from" to "to"
function _safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer();
}
} | burn | function burn(
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity);
if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage();
IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1));
_burn(msg.sender, liquidity);
}
| /// @inheritdoc IUniV3PairManager | NatSpecSingleLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
3085,
3565
]
} | 7,605 |
||||
UniV3PairManagerFactory | solidity/contracts/UniV3PairManager.sol | 0x005634cfef45e5a19c84aede6f0af17833471852 | Solidity | UniV3PairManager | contract UniV3PairManager is IUniV3PairManager, Governable {
/// @inheritdoc IERC20Metadata
string public override name;
/// @inheritdoc IERC20Metadata
string public override symbol;
/// @inheritdoc IERC20
uint256 public override totalSupply = 0;
/// @inheritdoc IPairManager
address public immutable override token0;
/// @inheritdoc IPairManager
address public immutable override token1;
/// @inheritdoc IPairManager
address public immutable override pool;
/// @inheritdoc IUniV3PairManager
uint24 public immutable override fee;
/// @inheritdoc IUniV3PairManager
uint160 public immutable override sqrtRatioAX96;
/// @inheritdoc IUniV3PairManager
uint160 public immutable override sqrtRatioBX96;
/// @notice Lowest possible tick in the Uniswap's curve
int24 private constant _TICK_LOWER = -887200;
/// @notice Highest possible tick in the Uniswap's curve
int24 private constant _TICK_UPPER = 887200;
/// @inheritdoc IERC20Metadata
//solhint-disable-next-line const-name-snakecase
uint8 public constant override decimals = 18;
/// @inheritdoc IERC20
mapping(address => mapping(address => uint256)) public override allowance;
/// @inheritdoc IERC20
mapping(address => uint256) public override balanceOf;
/// @notice Struct that contains token0, token1, and fee of the Uniswap pool
PoolAddress.PoolKey private _poolKey;
constructor(address _pool, address _governance) Governable(_governance) {
pool = _pool;
uint24 _fee = IUniswapV3Pool(_pool).fee();
fee = _fee;
address _token0 = IUniswapV3Pool(_pool).token0();
address _token1 = IUniswapV3Pool(_pool).token1();
token0 = _token0;
token1 = _token1;
name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol()));
symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol()));
sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER);
sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER);
_poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee});
}
// This low-level function should be called from a contract which performs important safety checks
/// @inheritdoc IUniV3PairManager
function mint(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint128 liquidity) {
(liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min);
_mint(to, liquidity);
}
/// @inheritdoc IUniV3PairManager
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external override {
MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
if (msg.sender != pool) revert OnlyPool();
if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed);
if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed);
}
/// @inheritdoc IUniV3PairManager
function burn(
uint128 liquidity,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity);
if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage();
IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1));
_burn(msg.sender, liquidity);
}
/// @inheritdoc IUniV3PairManager
function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) {
(, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions(
keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER))
);
(amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1);
}
/// @inheritdoc IUniV3PairManager
function position()
external
view
override
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
(liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions(
keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER))
);
}
/// @inheritdoc IERC20
function approve(address spender, uint256 amount) external override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/// @inheritdoc IERC20
function transfer(address to, uint256 amount) external override returns (bool) {
_transferTokens(msg.sender, to, amount);
return true;
}
/// @inheritdoc IERC20
function transferFrom(
address from,
address to,
uint256 amount
) external override returns (bool) {
address spender = msg.sender;
uint256 spenderAllowance = allowance[from][spender];
if (spender != from && spenderAllowance != type(uint256).max) {
uint256 newAllowance = spenderAllowance - amount;
allowance[from][spender] = newAllowance;
emit Approval(from, spender, newAllowance);
}
_transferTokens(from, to, amount);
return true;
}
/// @notice Adds liquidity to an initialized pool
/// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min
/// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback
/// @param amount0Desired The amount of token0 we would like to provide
/// @param amount1Desired The amount of token1 we would like to provide
/// @param amount0Min The minimum amount of token0 we want to provide
/// @param amount1Min The minimum amount of token1 we want to provide
/// @return liquidity The calculated liquidity we get for the token amounts we provided
/// @return amount0 The amount of token0 we ended up providing
/// @return amount1 The amount of token1 we ended up providing
function _addLiquidity(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min
)
internal
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired);
(amount0, amount1) = IUniswapV3Pool(pool).mint(
address(this),
_TICK_LOWER,
_TICK_UPPER,
liquidity,
abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender}))
);
if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage();
}
/// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value
/// @param token The token to be transferred to the recipient
/// @param from The address of the payer
/// @param to The address of the passed-in tokens recipient
/// @param value How much of that token to be transferred from payer to the recipient
function _pay(
address token,
address from,
address to,
uint256 value
) internal {
_safeTransferFrom(token, from, to, value);
}
/// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount
/// @param to The recipient of the Keep3r credits
/// @param amount The amount Keep3r credits to be minted to the recipient
function _mint(address to, uint256 amount) internal {
totalSupply += amount;
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
/// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount
/// @param to The address that will get its Keep3r credits burned
/// @param amount The amount Keep3r credits to be burned from the recipient/recipient
function _burn(address to, uint256 amount) internal {
totalSupply -= amount;
balanceOf[to] -= amount;
emit Transfer(to, address(0), amount);
}
/// @notice Transfers amount of Keep3r credits between two addresses
/// @param from The user that transfers the Keep3r credits
/// @param to The user that receives the Keep3r credits
/// @param amount The amount of Keep3r credits to be transferred
function _transferTokens(
address from,
address to,
uint256 amount
) internal {
balanceOf[from] -= amount;
balanceOf[to] += amount;
emit Transfer(from, to, amount);
}
/// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value
/// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful,
/// or if the passed data length is different than 0 and the decoded data is not a boolean
/// @param token The token to be transferred to the specified "to"
/// @param from The address which is going to transfer the tokens
/// @param value How much of that token to be transferred from "from" to "to"
function _safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer();
}
} | collect | function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) {
(, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions(
keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER))
);
(amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1);
}
| /// @inheritdoc IUniV3PairManager | NatSpecSingleLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
3603,
3993
]
} | 7,606 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.