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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CoreVault | contracts/CoreVault.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | CoreVault | contract CoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of COREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block.
uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The CORE TOKEN!
INBUNIERC20 public core;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _core,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 3000;
core = _core;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accCorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's COREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 20.00%
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending COREs on frontend.
function pendingCore(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCorePerShare = pool.accCorePerShare;
return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the CORE token.
// ----
uint256 private coreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance);
if(newRewards > 0) {
coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000);
uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee);
pool.accCorePerShare = pool.accCorePerShare.add(
coreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to CoreVault for CORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from CoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingCore(_pid, from);
if(pending > 0) {
safeCoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe core transfer function, just in case if rounding error causes pool to not have enough COREs.
function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
function transferDevFee() public {
if(pending_DEV_rewards == 0) return;
uint256 coreBal = core.balanceOf(address(this));
if (pending_DEV_rewards > coreBal) {
core.transfer(devaddr, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(devaddr, pending_DEV_rewards);
coreBalance = core.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | // Core Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | withdraw | function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
| // Withdraw tokens from CoreVault. | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
11440,
11572
]
} | 8,507 |
CoreVault | contracts/CoreVault.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | CoreVault | contract CoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of COREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block.
uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The CORE TOKEN!
INBUNIERC20 public core;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _core,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 3000;
core = _core;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accCorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's COREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 20.00%
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending COREs on frontend.
function pendingCore(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCorePerShare = pool.accCorePerShare;
return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the CORE token.
// ----
uint256 private coreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance);
if(newRewards > 0) {
coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000);
uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee);
pool.accCorePerShare = pool.accCorePerShare.add(
coreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to CoreVault for CORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from CoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingCore(_pid, from);
if(pending > 0) {
safeCoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe core transfer function, just in case if rounding error causes pool to not have enough COREs.
function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
function transferDevFee() public {
if(pending_DEV_rewards == 0) return;
uint256 coreBal = core.balanceOf(address(this));
if (pending_DEV_rewards > coreBal) {
core.transfer(devaddr, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(devaddr, pending_DEV_rewards);
coreBalance = core.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | // Core Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | _withdraw | function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
| // Low level withdraw function | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
11621,
12390
]
} | 8,508 |
CoreVault | contracts/CoreVault.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | CoreVault | contract CoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of COREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block.
uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The CORE TOKEN!
INBUNIERC20 public core;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _core,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 3000;
core = _core;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accCorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's COREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 20.00%
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending COREs on frontend.
function pendingCore(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCorePerShare = pool.accCorePerShare;
return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the CORE token.
// ----
uint256 private coreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance);
if(newRewards > 0) {
coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000);
uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee);
pool.accCorePerShare = pool.accCorePerShare.add(
coreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to CoreVault for CORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from CoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingCore(_pid, from);
if(pending > 0) {
safeCoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe core transfer function, just in case if rounding error causes pool to not have enough COREs.
function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
function transferDevFee() public {
if(pending_DEV_rewards == 0) return;
uint256 coreBal = core.balanceOf(address(this));
if (pending_DEV_rewards > coreBal) {
core.transfer(devaddr, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(devaddr, pending_DEV_rewards);
coreBalance = core.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | // Core Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | setStrategyContractOrDistributionContractAllowance | function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
| // function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
12992,
13427
]
} | 8,509 |
CoreVault | contracts/CoreVault.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | CoreVault | contract CoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of COREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block.
uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The CORE TOKEN!
INBUNIERC20 public core;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _core,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 3000;
core = _core;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accCorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's COREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 20.00%
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending COREs on frontend.
function pendingCore(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCorePerShare = pool.accCorePerShare;
return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the CORE token.
// ----
uint256 private coreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance);
if(newRewards > 0) {
coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000);
uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee);
pool.accCorePerShare = pool.accCorePerShare.add(
coreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to CoreVault for CORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from CoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingCore(_pid, from);
if(pending > 0) {
safeCoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe core transfer function, just in case if rounding error causes pool to not have enough COREs.
function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
function transferDevFee() public {
if(pending_DEV_rewards == 0) return;
uint256 coreBal = core.balanceOf(address(this));
if (pending_DEV_rewards > coreBal) {
core.transfer(devaddr, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(devaddr, pending_DEV_rewards);
coreBalance = core.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | // Core Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | emergencyWithdraw | function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
| // Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards! | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
13727,
14220
]
} | 8,510 |
CoreVault | contracts/CoreVault.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | CoreVault | contract CoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of COREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block.
uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The CORE TOKEN!
INBUNIERC20 public core;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _core,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 3000;
core = _core;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accCorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's COREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 20.00%
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending COREs on frontend.
function pendingCore(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCorePerShare = pool.accCorePerShare;
return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the CORE token.
// ----
uint256 private coreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance);
if(newRewards > 0) {
coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000);
uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee);
pool.accCorePerShare = pool.accCorePerShare.add(
coreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to CoreVault for CORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from CoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingCore(_pid, from);
if(pending > 0) {
safeCoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe core transfer function, just in case if rounding error causes pool to not have enough COREs.
function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
function transferDevFee() public {
if(pending_DEV_rewards == 0) return;
uint256 coreBal = core.balanceOf(address(this));
if (pending_DEV_rewards > coreBal) {
core.transfer(devaddr, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(devaddr, pending_DEV_rewards);
coreBalance = core.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | // Core Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | safeCoreTransfer | function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
| // Safe core transfer function, just in case if rounding error causes pool to not have enough COREs. | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
14329,
14834
]
} | 8,511 |
CoreVault | contracts/CoreVault.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | CoreVault | contract CoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of COREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block.
uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The CORE TOKEN!
INBUNIERC20 public core;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _core,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 3000;
core = _core;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accCorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's COREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 20.00%
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending COREs on frontend.
function pendingCore(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCorePerShare = pool.accCorePerShare;
return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the CORE token.
// ----
uint256 private coreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance);
if(newRewards > 0) {
coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000);
uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee);
pool.accCorePerShare = pool.accCorePerShare.add(
coreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to CoreVault for CORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from CoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingCore(_pid, from);
if(pending > 0) {
safeCoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe core transfer function, just in case if rounding error causes pool to not have enough COREs.
function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
function transferDevFee() public {
if(pending_DEV_rewards == 0) return;
uint256 coreBal = core.balanceOf(address(this));
if (pending_DEV_rewards > coreBal) {
core.transfer(devaddr, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(devaddr, pending_DEV_rewards);
coreBalance = core.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | // Core Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | setDevFeeReciever | function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
| // Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions. | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
15521,
15625
]
} | 8,512 |
CoreVault | contracts/CoreVault.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | CoreVault | contract CoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of COREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block.
uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The CORE TOKEN!
INBUNIERC20 public core;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _core,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 3000;
core = _core;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accCorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's COREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 20.00%
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending COREs on frontend.
function pendingCore(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCorePerShare = pool.accCorePerShare;
return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the CORE token.
// ----
uint256 private coreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance);
if(newRewards > 0) {
coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000);
uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee);
pool.accCorePerShare = pool.accCorePerShare.add(
coreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to CoreVault for CORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from CoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingCore(_pid, from);
if(pending > 0) {
safeCoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe core transfer function, just in case if rounding error causes pool to not have enough COREs.
function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
function transferDevFee() public {
if(pending_DEV_rewards == 0) return;
uint256 coreBal = core.balanceOf(address(this));
if (pending_DEV_rewards > coreBal) {
core.transfer(devaddr, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(devaddr, pending_DEV_rewards);
coreBalance = core.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | // Core Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | superAdmin | function superAdmin() public view returns (address) {
return _superAdmin;
}
| /**
* @dev Returns the address of the current super admin
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
15842,
15936
]
} | 8,513 |
CoreVault | contracts/CoreVault.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | CoreVault | contract CoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of COREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block.
uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The CORE TOKEN!
INBUNIERC20 public core;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _core,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 3000;
core = _core;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accCorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's COREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 20.00%
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending COREs on frontend.
function pendingCore(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCorePerShare = pool.accCorePerShare;
return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the CORE token.
// ----
uint256 private coreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance);
if(newRewards > 0) {
coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000);
uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee);
pool.accCorePerShare = pool.accCorePerShare.add(
coreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to CoreVault for CORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from CoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingCore(_pid, from);
if(pending > 0) {
safeCoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe core transfer function, just in case if rounding error causes pool to not have enough COREs.
function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
function transferDevFee() public {
if(pending_DEV_rewards == 0) return;
uint256 coreBal = core.balanceOf(address(this));
if (pending_DEV_rewards > coreBal) {
core.transfer(devaddr, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(devaddr, pending_DEV_rewards);
coreBalance = core.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | // Core Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | burnSuperAdmin | function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
| // Assisns super admint to address 0, making it unreachable forever | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
16246,
16411
]
} | 8,514 |
CoreVault | contracts/CoreVault.sol | 0x78aa057b7bf61092c6dbcafee728554b1a8d2f7c | Solidity | CoreVault | contract CoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of COREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accCorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. COREs to distribute per block.
uint256 accCorePerShare; // Accumulated COREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The CORE TOKEN!
INBUNIERC20 public core;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
//// pending rewards awaiting anyone to massUpdate
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) {
averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock));
}
// Returns averge fees in this epoch
function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) {
averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function startNewEpoch() public {
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value);
function initialize(
INBUNIERC20 _core,
address _devaddr,
address superAdmin
) public initializer {
OwnableUpgradeSafe.__Ownable_init();
DEV_FEE = 3000;
core = _core;
devaddr = _devaddr;
contractStartBlock = block.number;
_superAdmin = superAdmin;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function add(
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accCorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's COREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
function setPoolWithdrawable(
uint256 _pid,
bool _withdrawable
) public onlyOwner {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 20.00%
// Note contract owner is meant to be a governance contract allowing CORE governance consensus
uint16 DEV_FEE;
function setDevFee(uint16 _DEV_FEE) public onlyOwner {
require(_DEV_FEE <= 6000, 'Dev fee clamped at 20%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending COREs on frontend.
function pendingCore(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCorePerShare = pool.accCorePerShare;
return user.amount.mul(accCorePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
console.log("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.add(updatePool(pid));
}
pendingRewards = pendingRewards.sub(allRewards);
}
// ----
// Function that adds pending rewards, called by the CORE token.
// ----
uint256 private coreBalance;
function addPendingRewards(uint256 _) public {
uint256 newRewards = core.balanceOf(address(this)).sub(coreBalance);
if(newRewards > 0) {
coreBalance = core.balanceOf(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal returns (uint256 coreRewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
coreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.div(totalAllocPoint); // we can do this because pools are only mass updated
uint256 coreRewardFee = coreRewardWhole.mul(DEV_FEE).div(10000);
uint256 coreRewardToDistribute = coreRewardWhole.sub(coreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(coreRewardFee);
pool.accCorePerShare = pool.accCorePerShare.add(
coreRewardToDistribute.mul(1e12).div(tokenSupply)
);
}
// Deposit tokens to CoreVault for CORE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address depositFor, uint256 _pid, uint256 _amount) public {
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
massUpdatePools();
// Transfer pending tokens
// to user
updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12); /// This is deposited for address
emit Deposit(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public {
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount);
_withdraw(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from CoreVault.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
massUpdatePools();
updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming CORE farmed
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(address(to), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCorePerShare).div(1e12);
emit Withdraw(to, _pid, _amount);
}
function updateAndPayOutPending(uint256 _pid, address from) internal {
uint256 pending = pendingCore(_pid, from);
if(pending > 0) {
safeCoreTransfer(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked
function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin {
require(isContract(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).approve(contractAddress, _amount);
}
function isContract(address addr) public returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe core transfer function, just in case if rounding error causes pool to not have enough COREs.
function safeCoreTransfer(address _to, uint256 _amount) internal {
uint256 coreBal = core.balanceOf(address(this));
if (_amount > coreBal) {
core.transfer(_to, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(_to, _amount);
coreBalance = core.balanceOf(address(this));
}
//Avoids possible recursion loop
// proxy?
transferDevFee();
}
function transferDevFee() public {
if(pending_DEV_rewards == 0) return;
uint256 coreBal = core.balanceOf(address(this));
if (pending_DEV_rewards > coreBal) {
core.transfer(devaddr, coreBal);
coreBalance = core.balanceOf(address(this));
} else {
core.transfer(devaddr, pending_DEV_rewards);
coreBalance = core.balanceOf(address(this));
}
pending_DEV_rewards = 0;
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing CORE governance token holders to do this functions.
function setDevFeeReciever(address _devaddr) public onlyOwner {
devaddr = _devaddr;
}
address private _superAdmin;
event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current super admin
*/
function superAdmin() public view returns (address) {
return _superAdmin;
}
/**
* @dev Throws if called by any account other than the superAdmin
*/
modifier onlySuperAdmin() {
require(_superAdmin == _msgSender(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function burnSuperAdmin() public virtual onlySuperAdmin {
emit SuperAdminTransfered(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | // Core Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | newSuperAdmin | function newSuperAdmin(address newOwner) public virtual onlySuperAdmin {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SuperAdminTransfered(_superAdmin, newOwner);
_superAdmin = newOwner;
}
| // Super admin can transfer its powers to another address | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://fee948e0c253e51091a11a1674c7b7bfa37bff4ed79331560473d54d03c5af25 | {
"func_code_index": [
16477,
16737
]
} | 8,515 |
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
} | Ownable | function Ownable() public {
owner = msg.sender;
}
| /**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
261,
321
]
} | 8,516 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
} | transferOwnership | function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = 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.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
644,
820
]
} | 8,517 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | Pausable | contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
} | pause | function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
| /**
* @dev called by the owner to pause, triggers stopped state
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
513,
604
]
} | 8,518 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | Pausable | contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
} | unpause | function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
| /**
* @dev called by the owner to unpause, returns to normal state
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
688,
781
]
} | 8,519 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | transfer | function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
268,
659
]
} | 8,520 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
865,
977
]
} | 8,521 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | BurnableToken | contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
} | burn | function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
| /**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
222,
680
]
} | 8,522 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
| /**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
401,
853
]
} | 8,523 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | approve | function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
1485,
1675
]
} | 8,524 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | allowance | function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
1999,
2130
]
} | 8,525 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | increaseApproval | function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
2596,
2860
]
} | 8,526 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | decreaseApproval | function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
3331,
3741
]
} | 8,527 |
|||
DataWalletToken | DataWalletToken.sol | 0x8db54ca569d3019a2ba126d03c37c44b5ef81ef6 | Solidity | DataWalletToken | contract DataWalletToken is PausableToken, BurnableToken {
string public constant name = "DataWallet Token";
string public constant symbol = "DXT";
uint8 public constant decimals = 8;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals);
/**
* @dev DataWalletToken Constructor
*/
function DataWalletToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function transfer(address beneficiary, uint256 amount) public returns (bool) {
if (msg.sender != owner) {
require(!paused);
}
require(beneficiary != address(0));
require(amount <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[beneficiary] = balances[beneficiary].add(amount);
Transfer(msg.sender, beneficiary, amount);
return true;
}
} | DataWalletToken | function DataWalletToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
| /**
* @dev DataWalletToken Constructor
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://761563dcbd9e82808cee25a5850c4a1900586ada4f76bc058e65720e511809b1 | {
"func_code_index": [
349,
486
]
} | 8,528 |
|||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the amount of tokens in existence.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
90,
149
]
} | 8,529 |
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account) external view returns (uint256);
| /**
* @dev Returns the amount of tokens owned by `account`.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
228,
300
]
} | 8,530 |
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transfer | function transfer(address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
516,
597
]
} | 8,531 |
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | allowance | function allowance(address owner, address spender) external view returns (uint256);
| /**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
868,
955
]
} | 8,532 |
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 amount) external returns (bool);
| /**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
1604,
1682
]
} | 8,533 |
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
1985,
2086
]
} | 8,534 |
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | name | function name() public view returns (string memory) {
return _name;
}
| /**
* @dev Returns the name of the token.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
1031,
1116
]
} | 8,535 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | symbol | function symbol() public view returns (string memory) {
return _symbol;
}
| /**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
1225,
1314
]
} | 8,536 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | decimals | function decimals() public view returns (uint8) {
return _decimals;
}
| /**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
1877,
1962
]
} | 8,537 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | totalSupply | function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
| /**
* @dev See {IERC20-totalSupply}.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
2018,
2120
]
} | 8,538 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | balanceOf | function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
| /**
* @dev See {IERC20-balanceOf}.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
2174,
2295
]
} | 8,539 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | transfer | function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
| /**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
2494,
2780
]
} | 8,540 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | allowance | function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
| /**
* @dev See {IERC20-allowance}.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
2834,
2987
]
} | 8,541 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | approve | function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
| /**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
3121,
3303
]
} | 8,542 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
| /**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
3759,
4274
]
} | 8,543 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | increaseAllowance | function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
| /**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
4665,
4896
]
} | 8,544 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | decreaseAllowance | function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
| /**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
5379,
5661
]
} | 8,545 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | _transfer | function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| /**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
6131,
6607
]
} | 8,546 |
||
ERC20 | Token.sol | 0xf607728c2d2aeab52767041b78011659f4a4ac64 | Solidity | ERC20 | contract ERC20 is Permissions, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18 and a {totalSupply} of the token.
*
* All four of these values are immutable: they can only be set once during
* construction.
*/
constructor () public {
//_name = "Yield Link Finance;
//_symbol = "yLINK";
_name = "Yield Link Finance";
_symbol = "yLINK";
_decimals = 18;
_totalSupply = 40000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {balanceOf} and {transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
} | _approve | function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| /**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | None | ipfs://04529847981a094bf28da8e0c4246f4fb5c112a787a4cdcc3f01c3e49227c301 | {
"func_code_index": [
7028,
7372
]
} | 8,547 |
||
BondedECDSAKeep | @keep-network/sortition-pools/contracts/SortitionTree.sol | 0x9606879d3ad92c4564487fec261189ed4486e54c | Solidity | SortitionTree | contract SortitionTree {
using StackLib for uint256[];
using Branch for uint256;
using Position for uint256;
using Leaf for uint256;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
uint256 constant LEVELS = 7;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2 ** SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2 ** SLOT_WIDTH) - 1;
uint256 constant POOL_CAPACITY = SLOT_COUNT ** LEVELS;
////////////////////////////////////////////////////////////////////////////
// implicit tree
// root 8
// level2 64
// level3 512
// level4 4k
// level5 32k
// level6 256k
// level7 2M
uint256 root;
mapping(uint256 => mapping(uint256 => uint256)) branches;
mapping(uint256 => uint256) leaves;
// the flagged (see setFlag() and unsetFlag() in Position.sol) positions
// of all operators present in the pool
mapping(address => uint256) flaggedLeafPosition;
// the leaf after the rightmost occupied leaf of each stack
uint256 rightmostLeaf;
// the empty leaves in each stack
// between 0 and the rightmost occupied leaf
uint256[] emptyLeaves;
constructor() public {
root = 0;
rightmostLeaf = 0;
}
// checks if operator is already registered in the pool
function isOperatorRegistered(address operator) public view returns (bool) {
return getFlaggedLeafPosition(operator) != 0;
}
// Sum the number of operators in each trunk
function operatorsInPool() public view returns (uint256) {
// Get the number of leaves that might be occupied;
// if `rightmostLeaf` equals `firstLeaf()` the tree must be empty,
// otherwise the difference between these numbers
// gives the number of leaves that may be occupied.
uint256 nPossiblyUsedLeaves = rightmostLeaf;
// Get the number of empty leaves
// not accounted for by the `rightmostLeaf`
uint256 nEmptyLeaves = emptyLeaves.getSize();
return (nPossiblyUsedLeaves - nEmptyLeaves);
}
function totalWeight() public view returns (uint256) {
return root.sumWeight();
}
function insertOperator(address operator, uint256 weight) internal {
require(
!isOperatorRegistered(operator),
"Operator is already registered in the pool"
);
uint256 position = getEmptyLeafPosition();
// Record the block the operator was inserted in
uint256 theLeaf = Leaf.make(operator, block.number, weight);
root = setLeaf(position, theLeaf, root);
// Without position flags,
// the position 0x000000 would be treated as empty
flaggedLeafPosition[operator] = position.setFlag();
}
function removeOperator(address operator) internal {
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
require(
flaggedPosition != 0,
"Operator is not registered in the pool"
);
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
root = removeLeaf(unflaggedPosition, root);
removeLeafPositionRecord(operator);
}
function updateOperator(address operator, uint256 weight) internal {
require(
isOperatorRegistered(operator),
"Operator is not registered in the pool"
);
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
updateLeaf(unflaggedPosition, weight);
}
function removeLeafPositionRecord(address operator) internal {
flaggedLeafPosition[operator] = 0;
}
function getFlaggedLeafPosition(address operator)
internal
view
returns (uint256)
{
return flaggedLeafPosition[operator];
}
function removeLeaf(uint256 position, uint256 _root)
internal returns (uint256)
{
uint256 rightmostSubOne = rightmostLeaf - 1;
bool isRightmost = position == rightmostSubOne;
uint256 newRoot = setLeaf(position, 0, _root);
if (isRightmost) {
rightmostLeaf = rightmostSubOne;
} else {
emptyLeaves.stackPush(position);
}
return newRoot;
}
function updateLeaf(uint256 position, uint256 weight) internal {
uint256 oldLeaf = leaves[position];
if (oldLeaf.weight() != weight) {
uint256 newLeaf = oldLeaf.setWeight(weight);
root = setLeaf(position, newLeaf, root);
}
}
function setLeaf(uint256 position, uint256 theLeaf, uint256 _root)
internal returns (uint256)
{
uint256 childSlot;
uint256 treeNode;
uint256 newNode;
uint256 nodeWeight = theLeaf.weight();
// set leaf
leaves[position] = theLeaf;
uint256 parent = position;
// set levels 7 to 2
for (uint256 level = LEVELS; level >= 2; level--) {
childSlot = parent.slot();
parent = parent.parent();
treeNode = branches[level][parent];
newNode = treeNode.setSlot(childSlot, nodeWeight);
branches[level][parent] = newNode;
nodeWeight = newNode.sumWeight();
}
// set level Root
childSlot = parent.slot();
return _root.setSlot(childSlot, nodeWeight);
}
function pickWeightedLeaf(
uint256 index,
uint256 _root
) internal view returns (
uint256 leafPosition,
uint256 leafFirstIndex
) {
uint256 currentIndex = index;
uint256 currentNode = _root;
uint256 currentPosition = 0;
uint256 currentSlot;
require(index < currentNode.sumWeight(), "Index exceeds weight");
// get root slot
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(
currentIndex
);
// get slots from levels 2 to 7
for (uint256 level = 2; level <= LEVELS; level++) {
currentPosition = currentPosition.child(currentSlot);
currentNode = branches[level][currentPosition];
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(
currentIndex
);
}
// get leaf position
leafPosition = currentPosition.child(currentSlot);
// get the first index of the leaf
// This works because the last weight returned from `pickWeightedSlot()`
// equals the "overflow" from getting the current slot.
leafFirstIndex = index - currentIndex;
}
function getEmptyLeafPosition()
internal returns (uint256)
{
uint256 rLeaf = rightmostLeaf;
bool spaceOnRight = (rLeaf + 1) < POOL_CAPACITY;
if (spaceOnRight) {
rightmostLeaf = rLeaf + 1;
return rLeaf;
} else {
bool emptyLeavesInStack = leavesInStack();
require(emptyLeavesInStack, "Pool is full");
return emptyLeaves.stackPop();
}
}
function leavesInStack() internal view returns (bool) {
return emptyLeaves.getSize() > 0;
}
} | isOperatorRegistered | function isOperatorRegistered(address operator) public view returns (bool) {
return getFlaggedLeafPosition(operator) != 0;
}
| // checks if operator is already registered in the pool | LineComment | v0.5.17+commit.d19bba13 | MIT | bzzr://e8e8f6a9b347274bfa24d7a0bb7bdaa0d94987ea1344a7c5fdfee6222e3d5ad1 | {
"func_code_index": [
1739,
1879
]
} | 8,548 |
||
BondedECDSAKeep | @keep-network/sortition-pools/contracts/SortitionTree.sol | 0x9606879d3ad92c4564487fec261189ed4486e54c | Solidity | SortitionTree | contract SortitionTree {
using StackLib for uint256[];
using Branch for uint256;
using Position for uint256;
using Leaf for uint256;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
uint256 constant LEVELS = 7;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2 ** SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2 ** SLOT_WIDTH) - 1;
uint256 constant POOL_CAPACITY = SLOT_COUNT ** LEVELS;
////////////////////////////////////////////////////////////////////////////
// implicit tree
// root 8
// level2 64
// level3 512
// level4 4k
// level5 32k
// level6 256k
// level7 2M
uint256 root;
mapping(uint256 => mapping(uint256 => uint256)) branches;
mapping(uint256 => uint256) leaves;
// the flagged (see setFlag() and unsetFlag() in Position.sol) positions
// of all operators present in the pool
mapping(address => uint256) flaggedLeafPosition;
// the leaf after the rightmost occupied leaf of each stack
uint256 rightmostLeaf;
// the empty leaves in each stack
// between 0 and the rightmost occupied leaf
uint256[] emptyLeaves;
constructor() public {
root = 0;
rightmostLeaf = 0;
}
// checks if operator is already registered in the pool
function isOperatorRegistered(address operator) public view returns (bool) {
return getFlaggedLeafPosition(operator) != 0;
}
// Sum the number of operators in each trunk
function operatorsInPool() public view returns (uint256) {
// Get the number of leaves that might be occupied;
// if `rightmostLeaf` equals `firstLeaf()` the tree must be empty,
// otherwise the difference between these numbers
// gives the number of leaves that may be occupied.
uint256 nPossiblyUsedLeaves = rightmostLeaf;
// Get the number of empty leaves
// not accounted for by the `rightmostLeaf`
uint256 nEmptyLeaves = emptyLeaves.getSize();
return (nPossiblyUsedLeaves - nEmptyLeaves);
}
function totalWeight() public view returns (uint256) {
return root.sumWeight();
}
function insertOperator(address operator, uint256 weight) internal {
require(
!isOperatorRegistered(operator),
"Operator is already registered in the pool"
);
uint256 position = getEmptyLeafPosition();
// Record the block the operator was inserted in
uint256 theLeaf = Leaf.make(operator, block.number, weight);
root = setLeaf(position, theLeaf, root);
// Without position flags,
// the position 0x000000 would be treated as empty
flaggedLeafPosition[operator] = position.setFlag();
}
function removeOperator(address operator) internal {
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
require(
flaggedPosition != 0,
"Operator is not registered in the pool"
);
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
root = removeLeaf(unflaggedPosition, root);
removeLeafPositionRecord(operator);
}
function updateOperator(address operator, uint256 weight) internal {
require(
isOperatorRegistered(operator),
"Operator is not registered in the pool"
);
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
updateLeaf(unflaggedPosition, weight);
}
function removeLeafPositionRecord(address operator) internal {
flaggedLeafPosition[operator] = 0;
}
function getFlaggedLeafPosition(address operator)
internal
view
returns (uint256)
{
return flaggedLeafPosition[operator];
}
function removeLeaf(uint256 position, uint256 _root)
internal returns (uint256)
{
uint256 rightmostSubOne = rightmostLeaf - 1;
bool isRightmost = position == rightmostSubOne;
uint256 newRoot = setLeaf(position, 0, _root);
if (isRightmost) {
rightmostLeaf = rightmostSubOne;
} else {
emptyLeaves.stackPush(position);
}
return newRoot;
}
function updateLeaf(uint256 position, uint256 weight) internal {
uint256 oldLeaf = leaves[position];
if (oldLeaf.weight() != weight) {
uint256 newLeaf = oldLeaf.setWeight(weight);
root = setLeaf(position, newLeaf, root);
}
}
function setLeaf(uint256 position, uint256 theLeaf, uint256 _root)
internal returns (uint256)
{
uint256 childSlot;
uint256 treeNode;
uint256 newNode;
uint256 nodeWeight = theLeaf.weight();
// set leaf
leaves[position] = theLeaf;
uint256 parent = position;
// set levels 7 to 2
for (uint256 level = LEVELS; level >= 2; level--) {
childSlot = parent.slot();
parent = parent.parent();
treeNode = branches[level][parent];
newNode = treeNode.setSlot(childSlot, nodeWeight);
branches[level][parent] = newNode;
nodeWeight = newNode.sumWeight();
}
// set level Root
childSlot = parent.slot();
return _root.setSlot(childSlot, nodeWeight);
}
function pickWeightedLeaf(
uint256 index,
uint256 _root
) internal view returns (
uint256 leafPosition,
uint256 leafFirstIndex
) {
uint256 currentIndex = index;
uint256 currentNode = _root;
uint256 currentPosition = 0;
uint256 currentSlot;
require(index < currentNode.sumWeight(), "Index exceeds weight");
// get root slot
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(
currentIndex
);
// get slots from levels 2 to 7
for (uint256 level = 2; level <= LEVELS; level++) {
currentPosition = currentPosition.child(currentSlot);
currentNode = branches[level][currentPosition];
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(
currentIndex
);
}
// get leaf position
leafPosition = currentPosition.child(currentSlot);
// get the first index of the leaf
// This works because the last weight returned from `pickWeightedSlot()`
// equals the "overflow" from getting the current slot.
leafFirstIndex = index - currentIndex;
}
function getEmptyLeafPosition()
internal returns (uint256)
{
uint256 rLeaf = rightmostLeaf;
bool spaceOnRight = (rLeaf + 1) < POOL_CAPACITY;
if (spaceOnRight) {
rightmostLeaf = rLeaf + 1;
return rLeaf;
} else {
bool emptyLeavesInStack = leavesInStack();
require(emptyLeavesInStack, "Pool is full");
return emptyLeaves.stackPop();
}
}
function leavesInStack() internal view returns (bool) {
return emptyLeaves.getSize() > 0;
}
} | operatorsInPool | function operatorsInPool() public view returns (uint256) {
// Get the number of leaves that might be occupied;
// if `rightmostLeaf` equals `firstLeaf()` the tree must be empty,
// otherwise the difference between these numbers
// gives the number of leaves that may be occupied.
uint256 nPossiblyUsedLeaves = rightmostLeaf;
// Get the number of empty leaves
// not accounted for by the `rightmostLeaf`
uint256 nEmptyLeaves = emptyLeaves.getSize();
return (nPossiblyUsedLeaves - nEmptyLeaves);
}
| // Sum the number of operators in each trunk | LineComment | v0.5.17+commit.d19bba13 | MIT | bzzr://e8e8f6a9b347274bfa24d7a0bb7bdaa0d94987ea1344a7c5fdfee6222e3d5ad1 | {
"func_code_index": [
1930,
2506
]
} | 8,549 |
||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | HouseOwned | contract HouseOwned {
address house;
modifier onlyHouse {
require(msg.sender == house);
_;
}
/// @dev Contract constructor
function HouseOwned() public {
house = msg.sender;
}
} | HouseOwned | function HouseOwned() public {
house = msg.sender;
}
| /// @dev Contract constructor | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
166,
237
]
} | 8,550 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | Token | function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
| /// @dev Initializes contract with initial supply tokens to the creator of the contract | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
2142,
2275
]
} | 8,551 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | setJackpot | function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
| /// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
2413,
2970
]
} | 8,552 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | returnDeposit | function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
| /// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
3290,
3644
]
} | 8,553 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
| /// @dev Gets the balance of the specified address.
/// @param _owner The address | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
3739,
3859
]
} | 8,554 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | transfer | function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
| /// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
4094,
5210
]
} | 8,555 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
| /// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
5488,
5976
]
} | 8,556 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | approve | function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| /// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent. | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
6207,
6413
]
} | 8,557 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | allowance | function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
| /// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender. | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
6735,
6874
]
} | 8,558 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | increaseApproval | function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by. | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
7101,
7381
]
} | 8,559 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | decreaseApproval | function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by. | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
7613,
8063
]
} | 8,560 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | freezeDeposit | function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
| /// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
8335,
8801
]
} | 8,561 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | unfreezeDeposit | function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
| /// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data) | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
9067,
9437
]
} | 8,562 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | transferFromCroupier | function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
| /// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
9611,
9865
]
} | 8,563 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | _transfer | function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
| /// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
10100,
10635
]
} | 8,564 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Token | contract Token is HouseOwned, ERC20Interface {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public constant decimals = 0;
uint256 public supply;
// Trusted addresses
Jackpot public jackpot;
address public croupier;
// All users' balances
mapping (address => uint256) internal balances;
// Users' deposits with Croupier
mapping (address => uint256) public depositOf;
// Total amount of deposits
uint256 public totalDeposit;
// Total amount of "Frozen Deposit Pool" -- the tokens for sale at Croupier
uint256 public frozenPool;
// Allowance mapping
mapping (address => mapping (address => uint256)) internal allowed;
//////
/// @title Modifiers
//
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == croupier);
_;
}
/// @dev Only Jackpot
modifier onlyJackpot {
require(msg.sender == address(jackpot));
_;
}
/// @dev Protection from short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length == size + 4);
_;
}
//////
/// @title Events
//
/// @dev Fired when a token is burned (bet made)
event Burn(address indexed from, uint256 value);
/// @dev Fired when a deposit is made or withdrawn
/// direction == 0: deposit
/// direction == 1: withdrawal
event Deposit(address indexed from, uint256 value, uint8 direction, uint256 newDeposit);
/// @dev Fired when a deposit with Croupier is frozen (set for sale)
event DepositFrozen(address indexed from, uint256 value);
/// @dev Fired when a deposit with Croupier is unfrozen (removed from sale)
// Value is the resulting deposit, NOT the unfrozen amount
event DepositUnfrozen(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev Initializes contract with initial supply tokens to the creator of the contract
function Token() HouseOwned() public {
name = "JACK Token";
symbol = "JACK";
supply = 1000000;
}
/// @dev Function to set address of Jackpot contract once after creation
/// @param _jackpot Address of the Jackpot contract
function setJackpot(address _jackpot) onlyHouse public {
require(address(jackpot) == 0x0);
require(_jackpot != address(this)); // Protection from admin's mistake
jackpot = Jackpot(_jackpot);
uint256 bountyPortion = supply / 40; // 2.5% is the bounty portion for marketing expenses
balances[house] = bountyPortion; // House receives the bounty tokens
balances[jackpot] = supply - bountyPortion; // Jackpot gets the rest
croupier = jackpot.croupier();
}
//////
/// @title Public Methods
//
/// @dev Croupier invokes this method to return deposits to players
/// @param _to The address of the recipient
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier can return more than the user has actually deposited
function returnDeposit(address _to, uint256 _extra) onlyCroupier public {
require(depositOf[_to] > 0 || _extra > 0);
uint256 amount = depositOf[_to];
depositOf[_to] = 0;
totalDeposit = totalDeposit.sub(amount);
_transfer(croupier, _to, amount.add(_extra));
Deposit(_to, amount, 1, 0);
}
/// @dev Gets the balance of the specified address.
/// @param _owner The address
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() public view returns (uint256) {
return supply;
}
/// @dev Send `_value` tokens to `_to`
/// @param _to The address of the recipient
/// @param _value the amount to send
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(address(jackpot) != 0x0);
require(croupier != 0x0);
if (_to == address(jackpot)) {
// It is a token bet. Ignoring _value, only using 1 token
_burnFromAccount(msg.sender, 1);
jackpot.betToken(msg.sender);
return true;
}
if (_to == croupier && msg.sender != house) {
// It's a deposit to Croupier. In addition to transferring the token,
// mark it in the deposits table
// House can't make deposits. If House is transferring something to
// Croupier, it's just a transfer, nothing more
depositOf[msg.sender] += _value;
totalDeposit = totalDeposit.add(_value);
Deposit(msg.sender, _value, 0, depositOf[msg.sender]);
}
// In all cases but Jackpot transfer (which is terminated by a return), actually
// do perform the transfer
return _transfer(msg.sender, _to, _value);
}
/// @dev Transfer tokens from one address to another
/// @param _from address The address which you want to send tokens from
/// @param _to address The address which you want to transfer to
/// @param _value uint256 the amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
/// @param _spender The address which will spend the funds.
/// @param _value The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Function to check the amount of tokens that an owner allowed to a spender.
/// @param _owner address The address which owns the funds.
/// @param _spender address The address which will spend the funds.
/// @return A uint256 specifying the amount of tokens still available for the spender.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/// @dev Increase the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _addedValue The amount of tokens to increase the allowance by.
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Decrease the amount of tokens that an owner allowed to a spender.
/// @param _spender The address which will spend the funds.
/// @param _subtractedValue The amount of tokens to decrease the allowance by.
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/// @dev Croupier uses this method to set deposited credits of a player for sale
/// @param _user The address of the user
/// @param _extra Additional off-chain credit (AirDrop support), so that croupier could have frozen more than the user had invested
function freezeDeposit(address _user, uint256 _extra) onlyCroupier public {
require(depositOf[_user] > 0 || _extra > 0);
uint256 deposit = depositOf[_user];
depositOf[_user] = depositOf[_user].sub(deposit);
totalDeposit = totalDeposit.sub(deposit);
uint256 depositWithExtra = deposit.add(_extra);
frozenPool = frozenPool.add(depositWithExtra);
DepositFrozen(_user, depositWithExtra);
}
/// @dev Croupier uses this method stop selling user's tokens and return them to normal deposit
/// @param _user The user whose deposit is being unfrozen
/// @param _value The value to unfreeze according to Croupier's records (off-chain sale data)
function unfreezeDeposit(address _user, uint256 _value) onlyCroupier public {
require(_value > 0);
require(frozenPool >= _value);
depositOf[_user] = depositOf[_user].add(_value);
totalDeposit = totalDeposit.add(_value);
frozenPool = frozenPool.sub(_value);
DepositUnfrozen(_user, depositOf[_user]);
}
/// @dev The Jackpot contract invokes this method when selling tokens from Croupier
/// @param _to The recipient of the tokens
/// @param _value The amount
function transferFromCroupier(address _to, uint256 _value) onlyJackpot public {
require(_value > 0);
require(frozenPool >= _value);
frozenPool = frozenPool.sub(_value);
_transfer(croupier, _to, _value);
}
//////
/// @title Internal Methods
//
/// @dev Internal transfer function
/// @param _from From address
/// @param _to To address
/// @param _value The value to transfer
/// @return success
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(_to != address(0)); // Prevent transfer to 0x0 address
require(balances[_from] >= _value); // Check if the sender has enough
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
Transfer(_from, _to, _value);
return true;
}
/// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn
function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
} | _burnFromAccount | function _burnFromAccount(address _sender, uint256 _value) internal {
require(balances[_sender] >= _value); // Check if the sender has enough
balances[_sender] = balances[_sender].sub(_value); // Subtract from the sender
supply = supply.sub(_value); // Updates totalSupply
Burn(_sender, _value);
}
| /// @dev Internal function for burning tokens
/// @param _sender The token sender (whose tokens are being burned)
/// @param _value The amount of tokens to burn | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
10814,
11195
]
} | 8,565 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | Jackpot | function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
| /// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
3390,
3872
]
} | 8,566 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | setToken | function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
| /// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token) | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
4017,
4234
]
} | 8,567 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
| /// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
4598,
12550
]
} | 8,568 |
||||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | payOutJackpot | function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
| // Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
12772,
13265
]
} | 8,569 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | shouldBeTerminated | function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
| /// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
13620,
13786
]
} | 8,570 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | checkTermination | function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
| /// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
13942,
14600
]
} | 8,571 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | shouldBeStarted | function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
| /// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
14883,
15042
]
} | 8,572 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | checkGameStart | function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
| /// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
15188,
15391
]
} | 8,573 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | betToken | function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
| /// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
15555,
16028
]
} | 8,574 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | abort | function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
| /// @dev Allows House to terminate ICO as an emergency measure | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
16099,
16255
]
} | 8,575 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | claimRefund | function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
| /// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
16382,
16651
]
} | 8,576 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | killAborted | function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
| /// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
16787,
16960
]
} | 8,577 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | _terminationDuration | function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
| /// @dev Get current bid timer duration
/// @return duration The duration | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
17108,
17255
]
} | 8,578 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | _updateIcoPrice | function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
| /// @dev Updates the current ICO price according to the rules | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
17325,
17974
]
} | 8,579 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | _updateBetAmount | function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
| /// @dev Updates the current bid price according to the rules | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
18044,
18276
]
} | 8,580 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | _betTokensForEther | function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
| /// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
18443,
19133
]
} | 8,581 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | _icoTokensForEther | function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
| /// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
19308,
20213
]
} | 8,582 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | _flushEtherToCroupier | function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
| /// @dev Flush the currently pending Ether to Croupier | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
20276,
20549
]
} | 8,583 |
|||
Token | Token.sol | 0x861825daa0068136a55f6effb3f4a0b9aa17f51f | Solidity | Jackpot | contract Jackpot is HouseOwned {
using SafeMath for uint;
enum Stages {
InitialOffer, // ICO stage: forming the jackpot fund
GameOn, // The game is running
GameOver, // The jackpot is won, paying out the jackpot
Aborted // ICO aborted, refunding investments
}
uint256 constant initialIcoTokenPrice = 4 finney;
uint256 constant initialBetAmount = 10 finney;
uint constant gameStartJackpotThreshold = 333 ether;
uint constant icoTerminationTimeout = 48 hours;
// These variables hold the values needed for minor prize checking:
// - when they were last won (once the number reaches the corresponding amount, the
// minor prize is won, and it should be reset)
// - how much ether was bet since it was last won
// `etherSince*` variables start with value of 1 and always have +1 in their value
// so that the variables never go 0, for gas consumption consistency
uint32 public totalBets = 0;
uint256 public etherSince20 = 1;
uint256 public etherSince50 = 1;
uint256 public etherSince100 = 1;
uint256 public pendingEtherForCroupier = 0;
// ICO status
uint32 public icoSoldTokens;
uint256 public icoEndTime;
// Jackpot status
address public lastBetUser;
uint256 public terminationTime;
address public winner;
uint256 public pendingJackpotForHouse;
uint256 public pendingJackpotForWinner;
// General configuration and stage
address public croupier;
Token public token;
Stages public stage = Stages.InitialOffer;
// Price state
uint256 public currentIcoTokenPrice = initialIcoTokenPrice;
uint256 public currentBetAmount = initialBetAmount;
// Investment tracking for emergency ICO termination
mapping (address => uint256) public investmentOf;
uint256 public abortTime;
//////
/// @title Modifiers
//
/// @dev Only Token
modifier onlyToken {
require(msg.sender == address(token));
_;
}
/// @dev Only Croupier
modifier onlyCroupier {
require(msg.sender == address(croupier));
_;
}
//////
/// @title Events
//
/// @dev Fired when tokens are sold for Ether in ICO
event EtherIco(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when a bid with Ether is made
event EtherBet(address indexed from, uint256 value, uint256 dividends);
/// @dev Fired when a bid with a Token is made
event TokenBet(address indexed from);
/// @dev Fired when a bidder wins a minor prize
/// Type: 1: 20, 2: 50, 3: 100
event MinorPrizePayout(address indexed from, uint256 value, uint8 prizeType);
/// @dev Fired when as a result of ether bid, tokens are sold from the Croupier's pool
/// The parameters are who bought them, how many tokens, and for how much Ether they were sold
event SoldTokensFromCroupier(address indexed from, uint256 value, uint256 tokens);
/// @dev Fired when the jackpot is won
event JackpotWon(address indexed from, uint256 value);
//////
/// @title Constructor and Initialization
//
/// @dev The contract constructor
/// @param _croupier The address of the trusted Croupier bot's account
function Jackpot(address _croupier)
HouseOwned()
public
{
require(_croupier != 0x0);
croupier = _croupier;
// There are no bets (it even starts in ICO stage), so initialize
// lastBetUser, just so that value is not zero and is meaningful
// The game can't end until at least one bid is made, and once
// a bid is made, this value is permanently overwritten.
lastBetUser = _croupier;
}
/// @dev Function to set address of Token contract once after creation
/// @param _token Address of the Token contract (JACK Token)
function setToken(address _token) onlyHouse public {
require(address(token) == 0x0);
require(_token != address(this)); // Protection from admin's mistake
token = Token(_token);
}
//////
/// @title Default Function
//
/// @dev The fallback function for receiving ether (bets)
/// Action depends on stages:
/// - ICO: just sell the tokens
/// - Game: accept bets, award tokens, award minor (20, 50, 100) prizes
/// - Game Over: pay out jackpot
/// - Aborted: fail
function() payable public {
require(croupier != 0x0);
require(address(token) != 0x0);
require(stage != Stages.Aborted);
uint256 tokens;
if (stage == Stages.InitialOffer) {
// First, check if the ICO is over. If it is, trigger the events and
// refund sent ether
bool started = checkGameStart();
if (started) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
require(msg.value >= currentIcoTokenPrice);
// THE PLAN
// 1. [CHECK + EFFECT] Calculate how much times price, the investment amount is,
// calculate how many tokens the investor is going to get
// 2. [EFFECT] Log and count
// 3. [EFFECT] Check game start conditions and maybe start the game
// 4. [INT] Award the tokens
// 5. [INT] Transfer 20% to house
// 1. [CHECK + EFFECT] Checking the amount
tokens = _icoTokensForEther(msg.value);
// 2. [EFFECT] Log
// Log the ICO event and count investment
EtherIco(msg.sender, msg.value, tokens);
investmentOf[msg.sender] = investmentOf[msg.sender].add(
msg.value.sub(msg.value / 5)
);
// 3. [EFFECT] Game start
// Check if we have accumulated the jackpot amount required for game start
if (icoEndTime == 0 && this.balance >= gameStartJackpotThreshold) {
icoEndTime = now + icoTerminationTimeout;
}
// 4. [INT] Awarding tokens
// Award the deserved tokens (if any)
if (tokens > 0) {
token.transfer(msg.sender, tokens);
}
// 5. [INT] House
// House gets 20% of ICO according to the rules
house.transfer(msg.value / 5);
} else if (stage == Stages.GameOn) {
// First, check if the game is over. If it is, trigger the events and
// refund sent ether
bool terminated = checkTermination();
if (terminated) {
// Refund ether without failing the transaction
// (because side-effect is needed)
msg.sender.transfer(msg.value);
return;
}
// Now processing an Ether bid
require(msg.value >= currentBetAmount);
// THE PLAN
// 1. [CHECK] Calculate how much times min-bet, the bet amount is,
// calculate how many tokens the player is going to get
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// 3. [EFFECT] Deposit 25% to the Croupier (for dividends and house's benefit)
// 4. [EFFECT] Log and mark bid
// 6. [INT] Check and reward (if won) minor (20, 100, 1000) prizes
// 7. [EFFECT] Update bet amount
// 8. [INT] Award the tokens
// 1. [CHECK + EFFECT] Checking the bet amount and token reward
tokens = _betTokensForEther(msg.value);
// 2. [CHECK] Check how much is sold from the Croupier's pool, and how much from Jackpot
// The priority is (1) Croupier, (2) Jackpot
uint256 sellingFromJackpot = 0;
uint256 sellingFromCroupier = 0;
if (tokens > 0) {
uint256 croupierPool = token.frozenPool();
uint256 jackpotPool = token.balanceOf(this);
if (croupierPool == 0) {
// Simple case: only Jackpot is selling
sellingFromJackpot = tokens;
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
} else if (jackpotPool == 0 || tokens <= croupierPool) {
// Simple case: only Croupier is selling
// either because Jackpot has 0, or because Croupier takes over
// by priority and has enough tokens in its pool
sellingFromCroupier = tokens;
if (sellingFromCroupier > croupierPool) {
sellingFromCroupier = croupierPool;
}
} else {
// Complex case: both are selling now
sellingFromCroupier = croupierPool; // (tokens > croupierPool) is guaranteed at this point
sellingFromJackpot = tokens.sub(sellingFromCroupier);
if (sellingFromJackpot > jackpotPool) {
sellingFromJackpot = jackpotPool;
}
}
}
// 3. [EFFECT] Croupier deposit
// Transfer a portion to the Croupier for dividend payout and house benefit
// Dividends are a sum of:
// + 25% of bet
// + 50% of price of tokens sold from Jackpot (or just anything other than the bet and Croupier payment)
// + 0% of price of tokens sold from Croupier
// (that goes in SoldTokensFromCroupier instead)
uint256 tokenValue = msg.value.sub(currentBetAmount);
uint256 croupierSaleRevenue = 0;
if (sellingFromCroupier > 0) {
croupierSaleRevenue = tokenValue.div(
sellingFromJackpot.add(sellingFromCroupier)
).mul(sellingFromCroupier);
}
uint256 jackpotSaleRevenue = tokenValue.sub(croupierSaleRevenue);
uint256 dividends = (currentBetAmount.div(4)).add(jackpotSaleRevenue.div(2));
// 100% of money for selling from Croupier still goes to Croupier
// so that it's later paid out to the selling user
pendingEtherForCroupier = pendingEtherForCroupier.add(dividends.add(croupierSaleRevenue));
// 4. [EFFECT] Log and mark bid
// Log the bet with actual amount charged (value less change)
EtherBet(msg.sender, msg.value, dividends);
lastBetUser = msg.sender;
terminationTime = now + _terminationDuration();
// If anything was sold from Croupier, log it appropriately
if (croupierSaleRevenue > 0) {
SoldTokensFromCroupier(msg.sender, croupierSaleRevenue, sellingFromCroupier);
}
// 5. [INT] Minor prizes
// Check for winning minor prizes
_checkMinorPrizes(msg.sender, currentBetAmount);
// 6. [EFFECT] Update bet amount
_updateBetAmount();
// 7. [INT] Awarding tokens
if (sellingFromJackpot > 0) {
token.transfer(msg.sender, sellingFromJackpot);
}
if (sellingFromCroupier > 0) {
token.transferFromCroupier(msg.sender, sellingFromCroupier);
}
} else if (stage == Stages.GameOver) {
require(msg.sender == winner || msg.sender == house);
if (msg.sender == winner) {
require(pendingJackpotForWinner > 0);
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
msg.sender.transfer(winnersPay);
} else if (msg.sender == house) {
require(pendingJackpotForHouse > 0);
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
msg.sender.transfer(housePay);
}
}
}
// Croupier will call this function when the jackpot is won
// If Croupier fails to call the function for any reason, house and winner
// still can claim their jackpot portion by sending ether to Jackpot
function payOutJackpot() onlyCroupier public {
require(winner != 0x0);
if (pendingJackpotForHouse > 0) {
uint256 housePay = pendingJackpotForHouse;
pendingJackpotForHouse = 0;
house.transfer(housePay);
}
if (pendingJackpotForWinner > 0) {
uint256 winnersPay = pendingJackpotForWinner;
pendingJackpotForWinner = 0;
winner.transfer(winnersPay);
}
}
//////
/// @title Public Functions
//
/// @dev View function to check whether the game should be terminated
/// Used as internal function by checkTermination, as well as by the
/// Croupier bot, to check whether it should call checkTermination
/// @return Whether the game should be terminated by timeout
function shouldBeTerminated() public view returns (bool should) {
return stage == Stages.GameOn && terminationTime != 0 && now > terminationTime;
}
/// @dev Check whether the game should be terminated, and if it should, terminate it
/// @return Whether the game was terminated as the result
function checkTermination() public returns (bool terminated) {
if (shouldBeTerminated()) {
stage = Stages.GameOver;
winner = lastBetUser;
// Flush amount due for Croupier immediately
_flushEtherToCroupier();
// The rest should be claimed by the winner (except what house gets)
JackpotWon(winner, this.balance);
uint256 jackpot = this.balance;
pendingJackpotForHouse = jackpot.div(5);
pendingJackpotForWinner = jackpot.sub(pendingJackpotForHouse);
return true;
}
return false;
}
/// @dev View function to check whether the game should be started
/// Used as internal function by `checkGameStart`, as well as by the
/// Croupier bot, to check whether it should call `checkGameStart`
/// @return Whether the game should be started
function shouldBeStarted() public view returns (bool should) {
return stage == Stages.InitialOffer && icoEndTime != 0 && now > icoEndTime;
}
/// @dev Check whether the game should be started, and if it should, start it
/// @return Whether the game was started as the result
function checkGameStart() public returns (bool started) {
if (shouldBeStarted()) {
stage = Stages.GameOn;
return true;
}
return false;
}
/// @dev Bet 1 token in the game
/// The token has already been burned having passed all checks, so
/// just process the bet of 1 token
function betToken(address _user) onlyToken public {
// Token bets can only be accepted in the game stage
require(stage == Stages.GameOn);
bool terminated = checkTermination();
if (terminated) {
return;
}
TokenBet(_user);
lastBetUser = _user;
terminationTime = now + _terminationDuration();
// Check for winning minor prizes
_checkMinorPrizes(_user, 0);
}
/// @dev Allows House to terminate ICO as an emergency measure
function abort() onlyHouse public {
require(stage == Stages.InitialOffer);
stage = Stages.Aborted;
abortTime = now;
}
/// @dev In case the ICO is emergency-terminated by House, allows investors
/// to pull back the investments
function claimRefund() public {
require(stage == Stages.Aborted);
require(investmentOf[msg.sender] > 0);
uint256 payment = investmentOf[msg.sender];
investmentOf[msg.sender] = 0;
msg.sender.transfer(payment);
}
/// @dev In case the ICO was terminated, allows House to kill the contract in 2 months
/// after the termination date
function killAborted() onlyHouse public {
require(stage == Stages.Aborted);
require(now > abortTime + 60 days);
selfdestruct(house);
}
//////
/// @title Internal Functions
//
/// @dev Get current bid timer duration
/// @return duration The duration
function _terminationDuration() internal view returns (uint256 duration) {
return (5 + 19200 / (100 + totalBets)) * 1 minutes;
}
/// @dev Updates the current ICO price according to the rules
function _updateIcoPrice() internal {
uint256 newIcoTokenPrice = currentIcoTokenPrice;
if (icoSoldTokens < 10000) {
newIcoTokenPrice = 4 finney;
} else if (icoSoldTokens < 20000) {
newIcoTokenPrice = 5 finney;
} else if (icoSoldTokens < 30000) {
newIcoTokenPrice = 5.3 finney;
} else if (icoSoldTokens < 40000) {
newIcoTokenPrice = 5.7 finney;
} else {
newIcoTokenPrice = 6 finney;
}
if (newIcoTokenPrice != currentIcoTokenPrice) {
currentIcoTokenPrice = newIcoTokenPrice;
}
}
/// @dev Updates the current bid price according to the rules
function _updateBetAmount() internal {
uint256 newBetAmount = 10 finney + (totalBets / 100) * 6 finney;
if (newBetAmount != currentBetAmount) {
currentBetAmount = newBetAmount;
}
}
/// @dev Calculates how many tokens a user should get with a given Ether bid
/// @param value The bid amount
/// @return tokens The number of tokens
function _betTokensForEther(uint256 value) internal view returns (uint256 tokens) {
// One bet amount is for the bet itself, for the rest we will sell
// tokens
tokens = (value / currentBetAmount) - 1;
if (tokens >= 1000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 300) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 100) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 50) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 20) {
tokens = tokens + tokens / 20; // +5%
}
}
/// @dev Calculates how many tokens a user should get with a given ICO transfer
/// @param value The transfer amount
/// @return tokens The number of tokens
function _icoTokensForEther(uint256 value) internal returns (uint256 tokens) {
// How many times the input is greater than current token price
tokens = value / currentIcoTokenPrice;
if (tokens >= 10000) {
tokens = tokens + tokens / 4; // +25%
} else if (tokens >= 5000) {
tokens = tokens + tokens / 5; // +20%
} else if (tokens >= 1000) {
tokens = tokens + tokens / 7; // ~ +14.3%
} else if (tokens >= 500) {
tokens = tokens + tokens / 10; // +10%
} else if (tokens >= 200) {
tokens = tokens + tokens / 20; // +5%
}
// Checking if Jackpot has the tokens in reserve
if (tokens > token.balanceOf(this)) {
tokens = token.balanceOf(this);
}
icoSoldTokens += (uint32)(tokens);
_updateIcoPrice();
}
/// @dev Flush the currently pending Ether to Croupier
function _flushEtherToCroupier() internal {
if (pendingEtherForCroupier > 0) {
uint256 willTransfer = pendingEtherForCroupier;
pendingEtherForCroupier = 0;
croupier.transfer(willTransfer);
}
}
/// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value
function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
} | _checkMinorPrizes | function _checkMinorPrizes(address user, uint256 value) internal {
// First and foremost, increment the counters and ether counters
totalBets ++;
if (value > 0) {
etherSince20 = etherSince20.add(value);
etherSince50 = etherSince50.add(value);
etherSince100 = etherSince100.add(value);
}
// Now actually check if the bets won
uint256 etherPayout;
if ((totalBets + 30) % 100 == 0) {
// Won 100th
etherPayout = (etherSince100 - 1) / 10;
etherSince100 = 1;
MinorPrizePayout(user, etherPayout, 3);
user.transfer(etherPayout);
return;
}
if ((totalBets + 5) % 50 == 0) {
// Won 100th
etherPayout = (etherSince50 - 1) / 10;
etherSince50 = 1;
MinorPrizePayout(user, etherPayout, 2);
user.transfer(etherPayout);
return;
}
if (totalBets % 20 == 0) {
// Won 20th
etherPayout = (etherSince20 - 1) / 10;
etherSince20 = 1;
_flushEtherToCroupier();
MinorPrizePayout(user, etherPayout, 1);
user.transfer(etherPayout);
return;
}
return;
}
| /// @dev Count the bid towards minor prize fund, check if the user
/// wins a minor prize, and if they did, transfer the prize to them
/// @param user The user in question
/// @param value The bid value | NatSpecSingleLine | v0.4.19+commit.c4cbbb05 | bzzr://5e20faa37cf25032f2deb856869f27de24ff0d19b98fe1a21026b2aa09e7a648 | {
"func_code_index": [
20780,
22139
]
} | 8,584 |
|||
tokenGenerator | tokenGenerator.sol | 0xf72fd3f89a2bd2ca48859c7b3db96520ed65cd44 | Solidity | tokenGenerator | contract tokenGenerator 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(string memory _name, string memory _symbol, uint8 _decimals, uint _TotalSupply, address _address) public {
symbol =_symbol;
name = _name;
decimals = _decimals;
_totalSupply = _TotalSupply;
balances[_address] = _totalSupply;
emit Transfer(address(0), _address, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = 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 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external 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 view returns (uint) {
return _totalSupply - balances[address(0)];
}
| // ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------ | LineComment | v0.5.7+commit.6da8b019 | MIT | bzzr://782fb487508c12b8f4e0819926b7c27533ce9c5a9b0af72db76fbf9d868930c0 | {
"func_code_index": [
1001,
1118
]
} | 8,585 |
tokenGenerator | tokenGenerator.sol | 0xf72fd3f89a2bd2ca48859c7b3db96520ed65cd44 | Solidity | tokenGenerator | contract tokenGenerator 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(string memory _name, string memory _symbol, uint8 _decimals, uint _TotalSupply, address _address) public {
symbol =_symbol;
name = _name;
decimals = _decimals;
_totalSupply = _TotalSupply;
balances[_address] = _totalSupply;
emit Transfer(address(0), _address, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = 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 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external 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 view returns (uint balance) {
return balances[tokenOwner];
}
| // ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------ | LineComment | v0.5.7+commit.6da8b019 | MIT | bzzr://782fb487508c12b8f4e0819926b7c27533ce9c5a9b0af72db76fbf9d868930c0 | {
"func_code_index": [
1338,
1463
]
} | 8,586 |
tokenGenerator | tokenGenerator.sol | 0xf72fd3f89a2bd2ca48859c7b3db96520ed65cd44 | Solidity | tokenGenerator | contract tokenGenerator 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(string memory _name, string memory _symbol, uint8 _decimals, uint _TotalSupply, address _address) public {
symbol =_symbol;
name = _name;
decimals = _decimals;
_totalSupply = _TotalSupply;
balances[_address] = _totalSupply;
emit Transfer(address(0), _address, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = 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 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external 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.5.7+commit.6da8b019 | MIT | bzzr://782fb487508c12b8f4e0819926b7c27533ce9c5a9b0af72db76fbf9d868930c0 | {
"func_code_index": [
1807,
2089
]
} | 8,587 |
tokenGenerator | tokenGenerator.sol | 0xf72fd3f89a2bd2ca48859c7b3db96520ed65cd44 | Solidity | tokenGenerator | contract tokenGenerator 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(string memory _name, string memory _symbol, uint8 _decimals, uint _TotalSupply, address _address) public {
symbol =_symbol;
name = _name;
decimals = _decimals;
_totalSupply = _TotalSupply;
balances[_address] = _totalSupply;
emit Transfer(address(0), _address, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = 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 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external 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.5.7+commit.6da8b019 | MIT | bzzr://782fb487508c12b8f4e0819926b7c27533ce9c5a9b0af72db76fbf9d868930c0 | {
"func_code_index": [
2597,
2810
]
} | 8,588 |
tokenGenerator | tokenGenerator.sol | 0xf72fd3f89a2bd2ca48859c7b3db96520ed65cd44 | Solidity | tokenGenerator | contract tokenGenerator 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(string memory _name, string memory _symbol, uint8 _decimals, uint _TotalSupply, address _address) public {
symbol =_symbol;
name = _name;
decimals = _decimals;
_totalSupply = _TotalSupply;
balances[_address] = _totalSupply;
emit Transfer(address(0), _address, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = 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 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external 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.5.7+commit.6da8b019 | MIT | bzzr://782fb487508c12b8f4e0819926b7c27533ce9c5a9b0af72db76fbf9d868930c0 | {
"func_code_index": [
3341,
3704
]
} | 8,589 |
tokenGenerator | tokenGenerator.sol | 0xf72fd3f89a2bd2ca48859c7b3db96520ed65cd44 | Solidity | tokenGenerator | contract tokenGenerator 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(string memory _name, string memory _symbol, uint8 _decimals, uint _TotalSupply, address _address) public {
symbol =_symbol;
name = _name;
decimals = _decimals;
_totalSupply = _TotalSupply;
balances[_address] = _totalSupply;
emit Transfer(address(0), _address, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = 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 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external 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 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.5.7+commit.6da8b019 | MIT | bzzr://782fb487508c12b8f4e0819926b7c27533ce9c5a9b0af72db76fbf9d868930c0 | {
"func_code_index": [
3987,
4139
]
} | 8,590 |
tokenGenerator | tokenGenerator.sol | 0xf72fd3f89a2bd2ca48859c7b3db96520ed65cd44 | Solidity | tokenGenerator | contract tokenGenerator 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(string memory _name, string memory _symbol, uint8 _decimals, uint _TotalSupply, address _address) public {
symbol =_symbol;
name = _name;
decimals = _decimals;
_totalSupply = _TotalSupply;
balances[_address] = _totalSupply;
emit Transfer(address(0), _address, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = 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 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(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.5.7+commit.6da8b019 | MIT | bzzr://782fb487508c12b8f4e0819926b7c27533ce9c5a9b0af72db76fbf9d868930c0 | {
"func_code_index": [
4494,
4832
]
} | 8,591 |
tokenGenerator | tokenGenerator.sol | 0xf72fd3f89a2bd2ca48859c7b3db96520ed65cd44 | Solidity | tokenGenerator | contract tokenGenerator 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(string memory _name, string memory _symbol, uint8 _decimals, uint _TotalSupply, address _address) public {
symbol =_symbol;
name = _name;
decimals = _decimals;
_totalSupply = _TotalSupply;
balances[_address] = _totalSupply;
emit Transfer(address(0), _address, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = 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 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external 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 () external payable {
revert();
}
| // ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------ | LineComment | v0.5.7+commit.6da8b019 | MIT | bzzr://782fb487508c12b8f4e0819926b7c27533ce9c5a9b0af72db76fbf9d868930c0 | {
"func_code_index": [
5024,
5085
]
} | 8,592 |
|
tokenGenerator | tokenGenerator.sol | 0xf72fd3f89a2bd2ca48859c7b3db96520ed65cd44 | Solidity | tokenGenerator | contract tokenGenerator 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(string memory _name, string memory _symbol, uint8 _decimals, uint _TotalSupply, address _address) public {
symbol =_symbol;
name = _name;
decimals = _decimals;
_totalSupply = _TotalSupply;
balances[_address] = _totalSupply;
emit Transfer(address(0), _address, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = 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 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () external 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.5.7+commit.6da8b019 | MIT | bzzr://782fb487508c12b8f4e0819926b7c27533ce9c5a9b0af72db76fbf9d868930c0 | {
"func_code_index": [
5318,
5507
]
} | 8,593 |
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | SafeMath | library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
430,
723
]
} | 8,594 |
|
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | TokenERC20 | contract TokenERC20 is owned {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
uint256 val = _value * 10 ** uint256(decimals);
_transfer(msg.sender, _to, val);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
// Check if the sender has enough
balanceOf[msg.sender] -= _value;
// Subtract from the sender
totalSupply -= _value;
// Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other ccount
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
// Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]);
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the targeted balance
allowance[_from][msg.sender] -= _value;
// Subtract from the sender's allowance
totalSupply -= _value;
// Update totalSupply
emit Burn(_from, _value);
return true;
}
} | _transfer | function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
| /**
* Internal transfer, only can be called by this contract
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
937,
1784
]
} | 8,595 |
|||
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | TokenERC20 | contract TokenERC20 is owned {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
uint256 val = _value * 10 ** uint256(decimals);
_transfer(msg.sender, _to, val);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
// Check if the sender has enough
balanceOf[msg.sender] -= _value;
// Subtract from the sender
totalSupply -= _value;
// Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other ccount
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
// Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]);
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the targeted balance
allowance[_from][msg.sender] -= _value;
// Subtract from the sender's allowance
totalSupply -= _value;
// Update totalSupply
emit Burn(_from, _value);
return true;
}
} | transfer | function transfer(address _to, uint256 _value) public {
uint256 val = _value * 10 ** uint256(decimals);
_transfer(msg.sender, _to, val);
}
| /**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
1990,
2156
]
} | 8,596 |
|||
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | TokenERC20 | contract TokenERC20 is owned {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
uint256 val = _value * 10 ** uint256(decimals);
_transfer(msg.sender, _to, val);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
// Check if the sender has enough
balanceOf[msg.sender] -= _value;
// Subtract from the sender
totalSupply -= _value;
// Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other ccount
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
// Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]);
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the targeted balance
allowance[_from][msg.sender] -= _value;
// Subtract from the sender's allowance
totalSupply -= _value;
// Update totalSupply
emit Burn(_from, _value);
return true;
}
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| /**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
2677,
2983
]
} | 8,597 |
|||
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | TokenERC20 | contract TokenERC20 is owned {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
uint256 val = _value * 10 ** uint256(decimals);
_transfer(msg.sender, _to, val);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
// Check if the sender has enough
balanceOf[msg.sender] -= _value;
// Subtract from the sender
totalSupply -= _value;
// Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other ccount
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
// Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]);
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the targeted balance
allowance[_from][msg.sender] -= _value;
// Subtract from the sender's allowance
totalSupply -= _value;
// Update totalSupply
emit Burn(_from, _value);
return true;
}
} | approve | function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
| /**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
3247,
3419
]
} | 8,598 |
|||
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | TokenERC20 | contract TokenERC20 is owned {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
uint256 val = _value * 10 ** uint256(decimals);
_transfer(msg.sender, _to, val);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
// Check if the sender has enough
balanceOf[msg.sender] -= _value;
// Subtract from the sender
totalSupply -= _value;
// Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other ccount
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
// Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]);
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the targeted balance
allowance[_from][msg.sender] -= _value;
// Subtract from the sender's allowance
totalSupply -= _value;
// Update totalSupply
emit Burn(_from, _value);
return true;
}
} | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
| /**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
3813,
4157
]
} | 8,599 |
|||
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | TokenERC20 | contract TokenERC20 is owned {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
uint256 val = _value * 10 ** uint256(decimals);
_transfer(msg.sender, _to, val);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
// Check if the sender has enough
balanceOf[msg.sender] -= _value;
// Subtract from the sender
totalSupply -= _value;
// Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other ccount
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
// Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]);
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the targeted balance
allowance[_from][msg.sender] -= _value;
// Subtract from the sender's allowance
totalSupply -= _value;
// Update totalSupply
emit Burn(_from, _value);
return true;
}
} | burn | function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
// Check if the sender has enough
balanceOf[msg.sender] -= _value;
// Subtract from the sender
totalSupply -= _value;
// Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
| /**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
4327,
4699
]
} | 8,600 |
|||
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | TokenERC20 | contract TokenERC20 is owned {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
uint256 val = _value * 10 ** uint256(decimals);
_transfer(msg.sender, _to, val);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
// Check if the sender has enough
balanceOf[msg.sender] -= _value;
// Subtract from the sender
totalSupply -= _value;
// Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other ccount
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
// Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]);
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the targeted balance
allowance[_from][msg.sender] -= _value;
// Subtract from the sender's allowance
totalSupply -= _value;
// Update totalSupply
emit Burn(_from, _value);
return true;
}
} | burnFrom | function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
// Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]);
// Check allowance
balanceOf[_from] -= _value;
// Subtract from the targeted balance
allowance[_from][msg.sender] -= _value;
// Subtract from the sender's allowance
totalSupply -= _value;
// Update totalSupply
emit Burn(_from, _value);
return true;
}
| /**
* Destroy tokens from other ccount
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
4956,
5534
]
} | 8,601 |
|||
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | IonixxToken | contract IonixxToken is owned, TokenERC20 {
mapping(address => bool) public frozenAccount;
address contract_address;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {
owner = msg.sender;
contract_address = this;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
// Prevent transfer to 0x0 address. Use burn() instead
require(balanceOf[_from] >= _value);
// Check if the sender has enough
require(balanceOf[_to] + _value > balanceOf[_to]);
// Check for overflows
require(!frozenAccount[_from]);
// Check if sender is frozen
require(!frozenAccount[_to]);
// Check if recipient is frozen
balanceOf[_from] -= _value;
// Subtract from the sender
balanceOf[_to] += _value;
// Add the same to the recipient
emit Transfer(_from, _to, _value);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
} | _transfer | function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
// Prevent transfer to 0x0 address. Use burn() instead
require(balanceOf[_from] >= _value);
// Check if the sender has enough
require(balanceOf[_to] + _value > balanceOf[_to]);
// Check for overflows
require(!frozenAccount[_from]);
// Check if sender is frozen
require(!frozenAccount[_to]);
// Check if recipient is frozen
balanceOf[_from] -= _value;
// Subtract from the sender
balanceOf[_to] += _value;
// Add the same to the recipient
emit Transfer(_from, _to, _value);
}
| /* Internal transfer, only can be called by this contract */ | Comment | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
668,
1379
]
} | 8,602 |
|||
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | IonixxToken | contract IonixxToken is owned, TokenERC20 {
mapping(address => bool) public frozenAccount;
address contract_address;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {
owner = msg.sender;
contract_address = this;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
// Prevent transfer to 0x0 address. Use burn() instead
require(balanceOf[_from] >= _value);
// Check if the sender has enough
require(balanceOf[_to] + _value > balanceOf[_to]);
// Check for overflows
require(!frozenAccount[_from]);
// Check if sender is frozen
require(!frozenAccount[_to]);
// Check if recipient is frozen
balanceOf[_from] -= _value;
// Subtract from the sender
balanceOf[_to] += _value;
// Add the same to the recipient
emit Transfer(_from, _to, _value);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
} | mintToken | function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
| /// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
1571,
1839
]
} | 8,603 |
|||
IonixxToken | IonixxToken.sol | 0xfe448adf90e1d87c89178baa430ff3c6dd5406af | Solidity | IonixxToken | contract IonixxToken is owned, TokenERC20 {
mapping(address => bool) public frozenAccount;
address contract_address;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {
owner = msg.sender;
contract_address = this;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
// Prevent transfer to 0x0 address. Use burn() instead
require(balanceOf[_from] >= _value);
// Check if the sender has enough
require(balanceOf[_to] + _value > balanceOf[_to]);
// Check for overflows
require(!frozenAccount[_from]);
// Check if sender is frozen
require(!frozenAccount[_to]);
// Check if recipient is frozen
balanceOf[_from] -= _value;
// Subtract from the sender
balanceOf[_to] += _value;
// Add the same to the recipient
emit Transfer(_from, _to, _value);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
} | freezeAccount | function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
| /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://479dc6b6a120f3f4895be70c817ed13f0008fb6df65640b5c4164659310bf9d8 | {
"func_code_index": [
2020,
2186
]
} | 8,604 |
|||
Polyshiba | Polyshiba.sol | 0x1c90c1acee82550f51b1d96392dba2b0fa7640be | Solidity | Polyshiba | contract Polyshiba 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
// ------------------------------------------------------------------------
function Polyshiba() public {
symbol = "PLYSHIB";
name = "Polyshiba";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000;
balances[0x19B75A94Da9cfd70A6aB33d022f6a64E3CA3e7b0] = _totalSupply;
Transfer(address(0), 0x19B75A94Da9cfd70A6aB33d022f6a64E3CA3e7b0, _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);
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;
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);
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;
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 | Polyshiba | function Polyshiba() public {
symbol = "PLYSHIB";
name = "Polyshiba";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000;
balances[0x19B75A94Da9cfd70A6aB33d022f6a64E3CA3e7b0] = _totalSupply;
Transfer(address(0), 0x19B75A94Da9cfd70A6aB33d022f6a64E3CA3e7b0, _totalSupply);
}
| // ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------ | LineComment | v0.4.23+commit.124ca40d | None | bzzr://4cdaafd31451c084f5e8ae24113bc5c7ffeee34466bd6de96b87779c36f13604 | {
"func_code_index": [
456,
806
]
} | 8,605 |
Polyshiba | Polyshiba.sol | 0x1c90c1acee82550f51b1d96392dba2b0fa7640be | Solidity | Polyshiba | contract Polyshiba 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
// ------------------------------------------------------------------------
function Polyshiba() public {
symbol = "PLYSHIB";
name = "Polyshiba";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000;
balances[0x19B75A94Da9cfd70A6aB33d022f6a64E3CA3e7b0] = _totalSupply;
Transfer(address(0), 0x19B75A94Da9cfd70A6aB33d022f6a64E3CA3e7b0, _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);
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;
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);
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;
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.23+commit.124ca40d | None | bzzr://4cdaafd31451c084f5e8ae24113bc5c7ffeee34466bd6de96b87779c36f13604 | {
"func_code_index": [
994,
1115
]
} | 8,606 |
Subsets and Splits