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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ALCXRewarder | contracts/SushiToken.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | SushiToken | contract SushiToken is ERC20("SushiToken", "SUSHI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator =
keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal {
uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
} | // SushiToken with Governance. | LineComment | delegateBySig | function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator =
keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| /**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
2884,
3648
]
} | 1,300 |
||
ALCXRewarder | contracts/SushiToken.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | SushiToken | contract SushiToken is ERC20("SushiToken", "SUSHI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator =
keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal {
uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
} | // SushiToken with Governance. | LineComment | getCurrentVotes | function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
| /**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
3823,
4029
]
} | 1,301 |
||
ALCXRewarder | contracts/SushiToken.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | SushiToken | contract SushiToken is ERC20("SushiToken", "SUSHI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator =
keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal {
uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
} | // SushiToken with Governance. | LineComment | getPriorVotes | function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| /**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
4426,
5410
]
} | 1,302 |
||
GlassesLoot | glassesloot.sol | 0xae303c1506d03813e3950f649f53a9e5cc2c58e9 | Solidity | GlassesLoot | contract GlassesLoot is ERC721, Ownable, nonReentrant {
string public GLASSES_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN Glasses Loot from Space are sold out
uint256 public glassesPrice = 100000000000000000; // 0.1 ETH 75% of Mint goes back to the CommunityWallet! 20% of Royalties will go to the Community Wallet as well!
uint public constant maxGlassesPurchase = 20;
uint256 public constant MAX_GLASSES = 10000;
uint256 public budgetDev1 = 10000 ether;
uint256 public budgetCommunityWallet = 10000 ether;
bool public saleIsActive = false;
address private constant DEV1 = 0xb9Ac0254e09AfB0C18CBF21B6a2a490FB608e738;
address private constant CommunityWallet = 0x7ccAfc2707E88B5C9929a844d074a06eb1555DD7;
// mapping(uint => string) public glassesNames;
// Reserve Glasses for team - Giveaways/Prizes etc
uint public constant MAX_GLASSESRESERVE = 400; // total team reserves allowed for Giveaways, Admins, Mods, Team
uint public GlassesReserve = MAX_GLASSESRESERVE; // counter for team reserves remaining
constructor() ERC721("Glasses Loot", "GLOOT") { }
//TEAM Withdraw
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "Insufficent balance");
uint256 witdrawAmount = calculateWithdraw(budgetDev1,(balance * 25) / 100);
if (witdrawAmount>0){
budgetDev1 -= witdrawAmount;
_withdraw(DEV1, witdrawAmount);
}
witdrawAmount = calculateWithdraw(budgetCommunityWallet,(balance * 75) / 100);
if (witdrawAmount>0){
budgetCommunityWallet -= witdrawAmount;
_withdraw(CommunityWallet, witdrawAmount);
}
}
function calculateWithdraw(uint256 budget, uint256 proposal) private pure returns (uint256){
if (proposal>budget){
return budget;
} else{
return proposal;
}
}
function _withdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{ value: _amount }("");
require(success, "Failed to widthdraw Ether");
}
function setGlassesPrice(uint256 _glassesPrice) public onlyOwner {
glassesPrice = _glassesPrice;
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
GLASSES_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function reserveGlassesLoot(address _to, uint256 _reserveAmount) public onlyOwner {
uint reserveMint = MAX_GLASSESRESERVE - GlassesReserve;
require(_reserveAmount > 0 && _reserveAmount < GlassesReserve + 1, "Not enough reserve left to fulfill amount");
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, reserveMint + i);
}
GlassesReserve = GlassesReserve - _reserveAmount;
}
function mintGlassesLoot(uint numberOfTokens) public payable reentryLock {
require(saleIsActive, "Sale must be active to mint GlassesLoot");
require(numberOfTokens > 0 && numberOfTokens < maxGlassesPurchase + 1, "Can only mint 20 Glasses at a time");
require(totalSupply() + numberOfTokens < MAX_GLASSES - GlassesReserve + 1, "Purchase would exceed max supply of GlassesLoot");
require(msg.value >= glassesPrice * numberOfTokens, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply() + GlassesReserve; // start minting after reserved tokenIds
if (totalSupply() < MAX_GLASSES) {
_safeMint(msg.sender, mintIndex);
}
}
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
} | withdraw | function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "Insufficent balance");
uint256 witdrawAmount = calculateWithdraw(budgetDev1,(balance * 25) / 100);
if (witdrawAmount>0){
budgetDev1 -= witdrawAmount;
_withdraw(DEV1, witdrawAmount);
}
witdrawAmount = calculateWithdraw(budgetCommunityWallet,(balance * 75) / 100);
if (witdrawAmount>0){
budgetCommunityWallet -= witdrawAmount;
_withdraw(CommunityWallet, witdrawAmount);
}
}
| //TEAM Withdraw | LineComment | v0.8.12+commit.f00d7308 | MIT | ipfs://1e3421184492e9d5714380967d08a1452e387840730fab01fc4a97f09821f0cf | {
"func_code_index": [
1188,
1800
]
} | 1,303 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | setPendingGovernance | function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
| /// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
2113,
2399
]
} | 1,304 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | setRewardRate | function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
| /// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
2829,
2994
]
} | 1,305 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | createPool | function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
| /// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
3267,
3760
]
} | 1,306 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | setRewardWeights | function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
| /// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
3889,
4679
]
} | 1,307 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | deposit | function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
| /// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
4843,
5128
]
} | 1,308 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | withdraw | function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
| /// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
5315,
5623
]
} | 1,309 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | claim | function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
| /// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
5821,
6062
]
} | 1,310 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | exit | function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
| /// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
6191,
6476
]
} | 1,311 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | rewardRate | function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
| /// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
6590,
6675
]
} | 1,312 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | totalRewardWeight | function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
| /// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
6782,
6881
]
} | 1,313 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | poolCount | function poolCount() external view returns (uint256) {
return _pools.length();
}
| /// @dev Gets the number of pools that exist.
///
/// @return the pool count. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
6964,
7048
]
} | 1,314 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | getPoolToken | function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
| /// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
7173,
7319
]
} | 1,315 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | getPoolTotalDeposited | function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
| /// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
7499,
7664
]
} | 1,316 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | getPoolRewardWeight | function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
| /// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
7874,
8035
]
} | 1,317 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | getPoolRewardRate | function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
| /// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
8217,
8383
]
} | 1,318 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | getStakeTotalDeposited | function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
| /// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
8599,
8793
]
} | 1,319 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | getStakeTotalUnclaimed | function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
| /// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
9089,
9320
]
} | 1,320 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | _updatePools | function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
| /// @dev Updates all of the pools. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
9358,
9541
]
} | 1,321 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | _deposit | function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
| /// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
9780,
10237
]
} | 1,322 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | _withdraw | function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
| /// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
10499,
10943
]
} | 1,323 |
||
ALCXRewarder | contracts/StakingPools.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | StakingPools | contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
} | ///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap. | NatSpecSingleLine | _claim | function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
| /// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
11216,
11501
]
} | 1,324 |
||
ProxyUpgradeableOwnable | @solidstate/contracts/proxy/Proxy.sol | 0xc4b2c51f969e0713e799de73b7f130fb7bb604cf | Solidity | Proxy | abstract contract Proxy {
using AddressUtils for address;
/**
* @notice delegate all calls to implementation contract
* @dev reverts if implementation address contains no code, for compatibility with metamorphic contracts
* @dev memory location in use by assembly may be unsafe in other contexts
*/
fallback() external payable virtual {
address implementation = _getImplementation();
require(
implementation.isContract(),
'Proxy: implementation must be contract'
);
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(
gas(),
implementation,
0,
calldatasize(),
0,
0
)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice get logic implementation address
* @return implementation address
*/
function _getImplementation() internal virtual returns (address);
} | /**
* @title Base proxy contract
*/ | NatSpecMultiLine | /**
* @notice delegate all calls to implementation contract
* @dev reverts if implementation address contains no code, for compatibility with metamorphic contracts
* @dev memory location in use by assembly may be unsafe in other contexts
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | {
"func_code_index": [
328,
1064
]
} | 1,325 |
||||
ProxyUpgradeableOwnable | @solidstate/contracts/proxy/Proxy.sol | 0xc4b2c51f969e0713e799de73b7f130fb7bb604cf | Solidity | Proxy | abstract contract Proxy {
using AddressUtils for address;
/**
* @notice delegate all calls to implementation contract
* @dev reverts if implementation address contains no code, for compatibility with metamorphic contracts
* @dev memory location in use by assembly may be unsafe in other contexts
*/
fallback() external payable virtual {
address implementation = _getImplementation();
require(
implementation.isContract(),
'Proxy: implementation must be contract'
);
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(
gas(),
implementation,
0,
calldatasize(),
0,
0
)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice get logic implementation address
* @return implementation address
*/
function _getImplementation() internal virtual returns (address);
} | /**
* @title Base proxy contract
*/ | NatSpecMultiLine | _getImplementation | function _getImplementation() internal virtual returns (address);
| /**
* @notice get logic implementation address
* @return implementation address
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | {
"func_code_index": [
1168,
1237
]
} | 1,326 |
||
ProxyUpgradeableOwnable | @solidstate/contracts/access/IERC173.sol | 0xc4b2c51f969e0713e799de73b7f130fb7bb604cf | Solidity | IERC173 | interface IERC173 {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @notice get the ERC173 contract owner
* @return conract owner
*/
function owner() external view returns (address);
/**
* @notice transfer contract ownership to new account
* @param account address of new owner
*/
function transferOwnership(address account) external;
} | /**
* @title Contract ownership standard interface
* @dev see https://eips.ethereum.org/EIPS/eip-173
*/ | NatSpecMultiLine | owner | function owner() external view returns (address);
| /**
* @notice get the ERC173 contract owner
* @return conract owner
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | {
"func_code_index": [
222,
275
]
} | 1,327 |
||
ProxyUpgradeableOwnable | @solidstate/contracts/access/IERC173.sol | 0xc4b2c51f969e0713e799de73b7f130fb7bb604cf | Solidity | IERC173 | interface IERC173 {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @notice get the ERC173 contract owner
* @return conract owner
*/
function owner() external view returns (address);
/**
* @notice transfer contract ownership to new account
* @param account address of new owner
*/
function transferOwnership(address account) external;
} | /**
* @title Contract ownership standard interface
* @dev see https://eips.ethereum.org/EIPS/eip-173
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address account) external;
| /**
* @notice transfer contract ownership to new account
* @param account address of new owner
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | {
"func_code_index": [
394,
451
]
} | 1,328 |
||
ProxyUpgradeableOwnable | @solidstate/contracts/access/Ownable.sol | 0xc4b2c51f969e0713e799de73b7f130fb7bb604cf | Solidity | Ownable | abstract contract Ownable is IERC173, OwnableInternal {
using OwnableStorage for OwnableStorage.Layout;
/**
* @inheritdoc IERC173
*/
function owner() public view virtual override returns (address) {
return OwnableStorage.layout().owner;
}
/**
* @inheritdoc IERC173
*/
function transferOwnership(address account)
public
virtual
override
onlyOwner
{
OwnableStorage.layout().setOwner(account);
emit OwnershipTransferred(msg.sender, account);
}
} | /**
* @title Ownership access control based on ERC173
*/ | NatSpecMultiLine | owner | function owner() public view virtual override returns (address) {
return OwnableStorage.layout().owner;
}
| /**
* @inheritdoc IERC173
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | {
"func_code_index": [
152,
273
]
} | 1,329 |
||
ProxyUpgradeableOwnable | @solidstate/contracts/access/Ownable.sol | 0xc4b2c51f969e0713e799de73b7f130fb7bb604cf | Solidity | Ownable | abstract contract Ownable is IERC173, OwnableInternal {
using OwnableStorage for OwnableStorage.Layout;
/**
* @inheritdoc IERC173
*/
function owner() public view virtual override returns (address) {
return OwnableStorage.layout().owner;
}
/**
* @inheritdoc IERC173
*/
function transferOwnership(address account)
public
virtual
override
onlyOwner
{
OwnableStorage.layout().setOwner(account);
emit OwnershipTransferred(msg.sender, account);
}
} | /**
* @title Ownership access control based on ERC173
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address account)
public
virtual
override
onlyOwner
{
OwnableStorage.layout().setOwner(account);
emit OwnershipTransferred(msg.sender, account);
}
| /**
* @inheritdoc IERC173
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | {
"func_code_index": [
318,
550
]
} | 1,330 |
||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
| /**
* @dev Multiplies two numbers, reverts on overflow.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
92,
488
]
} | 1,331 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
600,
877
]
} | 1,332 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
| /**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
994,
1131
]
} | 1,333 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
| /**
* @dev Adds two numbers, reverts on overflow.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1198,
1335
]
} | 1,334 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
| /**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1473,
1590
]
} | 1,335 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view returns (uint256) {
return _totalSupply;
}
| /**
* @dev Total number of tokens in existence
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
281,
369
]
} | 1,336 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
574,
677
]
} | 1,337 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | 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.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
999,
1174
]
} | 1,338 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | transfer | function transfer(address to, uint256 value) public returns (bool) {
_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.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1334,
1467
]
} | 1,339 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
| /**
* @dev 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.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2091,
2312
]
} | 1,340 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | transferFrom | function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_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.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2577,
2859
]
} | 1,341 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | increaseAllowance | function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
| /**
* @dev 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.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
3318,
3650
]
} | 1,342 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | decreaseAllowance | function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
| /**
* @dev 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.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
4114,
4456
]
} | 1,343 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | _transfer | function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| /**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
4671,
4958
]
} | 1,344 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | _mint | function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
| /**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
5291,
5534
]
} | 1,345 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | _burn | function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
| /**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
5752,
6040
]
} | 1,346 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev 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) {
_transfer(msg.sender, 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | _burnFrom | function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
| /**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
6350,
6753
]
} | 1,347 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Roles | library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
} | /**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/ | NatSpecMultiLine | add | function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
| /**
* @dev give an account access to this role
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
141,
279
]
} | 1,348 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Roles | library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
} | /**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/ | NatSpecMultiLine | remove | function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
| /**
* @dev remove an account's access to this role
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
347,
489
]
} | 1,349 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Roles | library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
} | /**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/ | NatSpecMultiLine | has | function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
| /**
* @dev check if an account has this role
* @return bool
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
570,
740
]
} | 1,350 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | ERC20Mintable | contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
} | /**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/ | NatSpecMultiLine | mint | function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
| /**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
282,
433
]
} | 1,351 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | function () external payable {
buyTokens(msg.sender);
}
| /**
* @dev fallback function ***DO NOT OVERRIDE***
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1814,
1880
]
} | 1,352 |
||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | token | function token() public view returns(IERC20) {
return _token;
}
| /**
* @return the token being sold.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1933,
2007
]
} | 1,353 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | wallet | function wallet() public view returns(address) {
return _wallet;
}
| /**
* @return the address where funds are collected.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2077,
2154
]
} | 1,354 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | rate | function rate() public view returns(uint256) {
return _rate;
}
| /**
* @return the number of token units a buyer gets per wei.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2233,
2306
]
} | 1,355 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | weiRaised | function weiRaised() public view returns (uint256) {
return _weiRaised;
}
| /**
* @return the mount of wei raised.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2362,
2446
]
} | 1,356 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | buyTokens | function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
| /**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2584,
3185
]
} | 1,357 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _preValidatePurchase | function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
| /**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
3841,
4021
]
} | 1,358 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _postValidatePurchase | function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
| /**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
4297,
4433
]
} | 1,359 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _deliverTokens | function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
| /**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
4694,
4851
]
} | 1,360 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _processPurchase | function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
| /**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
5096,
5250
]
} | 1,361 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _updatePurchasingState | function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
| /**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
5502,
5639
]
} | 1,362 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _getTokenAmount | function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
| /**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
5877,
6002
]
} | 1,363 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Crowdsale | contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor(uint256 rate, address wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(token != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
} | /**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing players to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/ | NatSpecMultiLine | _forwardFunds | function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
| /**
* @dev Determines how ETH is stored/forwarded on purchases.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
6083,
6160
]
} | 1,364 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | TimedCrowdsale | contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 internal _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "Crowdsale is no longer open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor(uint256 openingTime, uint256 closingTime) public {
// solium-disable-next-line security/no-block-members
require(openingTime >= block.timestamp, "The Crowdsale must not start in the past");
require(closingTime >= openingTime, "The Crowdsale must end in the future");
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns(uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns(uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(beneficiary, weiAmount);
}
} | /**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/ | NatSpecMultiLine | openingTime | function openingTime() public view returns(uint256) {
return _openingTime;
}
| /**
* @return the crowdsale opening time.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
910,
997
]
} | 1,365 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | TimedCrowdsale | contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 internal _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "Crowdsale is no longer open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor(uint256 openingTime, uint256 closingTime) public {
// solium-disable-next-line security/no-block-members
require(openingTime >= block.timestamp, "The Crowdsale must not start in the past");
require(closingTime >= openingTime, "The Crowdsale must end in the future");
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns(uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns(uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(beneficiary, weiAmount);
}
} | /**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/ | NatSpecMultiLine | closingTime | function closingTime() public view returns(uint256) {
return _closingTime;
}
| /**
* @return the crowdsale closing time.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1056,
1143
]
} | 1,366 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | TimedCrowdsale | contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 internal _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "Crowdsale is no longer open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor(uint256 openingTime, uint256 closingTime) public {
// solium-disable-next-line security/no-block-members
require(openingTime >= block.timestamp, "The Crowdsale must not start in the past");
require(closingTime >= openingTime, "The Crowdsale must end in the future");
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns(uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns(uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(beneficiary, weiAmount);
}
} | /**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/ | NatSpecMultiLine | isOpen | function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
| /**
* @return true if the crowdsale is open, false otherwise.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1222,
1415
]
} | 1,367 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | TimedCrowdsale | contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 internal _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "Crowdsale is no longer open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor(uint256 openingTime, uint256 closingTime) public {
// solium-disable-next-line security/no-block-members
require(openingTime >= block.timestamp, "The Crowdsale must not start in the past");
require(closingTime >= openingTime, "The Crowdsale must end in the future");
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns(uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns(uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(beneficiary, weiAmount);
}
} | /**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/ | NatSpecMultiLine | hasClosed | function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > _closingTime;
}
| /**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1572,
1732
]
} | 1,368 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | TimedCrowdsale | contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 internal _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "Crowdsale is no longer open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor(uint256 openingTime, uint256 closingTime) public {
// solium-disable-next-line security/no-block-members
require(openingTime >= block.timestamp, "The Crowdsale must not start in the past");
require(closingTime >= openingTime, "The Crowdsale must end in the future");
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns(uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns(uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > _closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(beneficiary, weiAmount);
}
} | /**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/ | NatSpecMultiLine | _preValidatePurchase | function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(beneficiary, weiAmount);
}
| /**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1916,
2099
]
} | 1,369 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | MintedCrowdsale | contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param beneficiary Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(token())).mint(beneficiary, tokenAmount));
}
} | /**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/ | NatSpecMultiLine | _deliverTokens | function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(token())).mint(beneficiary, tokenAmount));
}
| /**
* @dev Overrides delivery by minting tokens upon purchase.
* @param beneficiary Token purchaser
* @param tokenAmount Number of tokens to be minted
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
216,
477
]
} | 1,370 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Must be owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Must provide a valid owner address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | owner | function owner() public view returns(address) {
return _owner;
}
| /**
* @return the address of the owner.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
437,
512
]
} | 1,371 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Must be owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Must provide a valid owner address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | isOwner | function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
| /**
* @return true if `msg.sender` is the owner of the contract.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
752,
840
]
} | 1,372 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Must be owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Must provide a valid owner address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1108,
1241
]
} | 1,373 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Must be owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Must provide a valid owner address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1405,
1511
]
} | 1,374 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Must be owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Must provide a valid owner address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | _transferOwnership | function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Must provide a valid owner address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1648,
1862
]
} | 1,375 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | percent | function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
| /**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1677,
2036
]
} | 1,376 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
| /**
* @dev wallet can receive funds.
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2088,
2190
]
} | 1,377 |
||||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | sendTo | function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
| /**
* @dev wallet can send funds
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2238,
2555
]
} | 1,378 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | balanceOf | function balanceOf() public view returns (uint256) {
return address(this).balance;
}
| /**
* @dev function to see the balance of Ether in the wallet
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2632,
2727
]
} | 1,379 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | redeemTokens | function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
| /**
* @dev function for the player to cash in tokens
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2795,
4133
]
} | 1,380 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | acceptedToken | function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
| // checks if a token is an accepted game token | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
4186,
4312
]
} | 1,381 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | calculateTokensIssued | function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
| /**
* @dev functions to calculate game results and payouts
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
4386,
4574
]
} | 1,382 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | calculateOracleFee | function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
| // "15" in this function means 15%. Change that number to raise or lower
// the oracle fee. | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
5003,
5129
]
} | 1,383 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | calculateTotalPlayerRewards | function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
| // this calculates how much Ether is available for player rewards | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
5201,
5320
]
} | 1,384 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | calculateTotalBoxOffice | function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
| // this calculates the total box office earnings of all movies in USD | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
5396,
5695
]
} | 1,385 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | calculateTotalPlayerRewardsPerMovie | function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
| // this calculates how much Ether to reward for each game token | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
5765,
6202
]
} | 1,386 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | calculateGameResults | function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
| /**
* @dev add box office results and token addresses for the movies, and calculate game results
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
6873,
8042
]
} | 1,387 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameMaster | contract PickflixGameMaster is Ownable {
// this library helps protect against overflows for large integers
using SafeMath for uint256;
// fires off events for receiving and sending Ether
event Sent(address indexed payee, uint256 amount, uint256 balance);
event Received(address indexed payer, uint256 amount, uint256 balance);
string public gameName;
uint public openDate;
uint public closeDate;
bool public gameDone;
// create a mapping for box office totals for particular movies
// address is the token contract address
mapping (address => uint256) public boxOfficeTotals;
// let's make a Movie struct to make all of this code cleaner
struct Movie {
uint256 boxOfficeTotal;
uint256 totalPlayerRewards;
bool accepted;
}
// map token addresses to Movie structs
mapping (address => Movie) public movies;
// count the total number of tokens issued
uint256 public tokensIssued = 0; // this number will change
// more global variables, for calculating payouts and game results
uint256 public oracleFee = 0;
uint256 public oracleFeePercent = 0;
uint256 public totalPlayerRewards = 0;
uint256 public totalBoxOffice = 0;
// owner is set to original message sender during contract migration
constructor(string _gameName, uint _closeDate, uint _oracleFeePercent) Ownable() public {
gameName = _gameName;
closeDate = _closeDate;
openDate = block.timestamp;
gameDone = false;
oracleFeePercent = _oracleFeePercent;
}
/**
* calculate a percentage with parts per notation.
* the value returned will be in terms of 10e precision
*/
function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) {
// caution, keep this a private function so the numbers are safe
uint _numerator = (numerator * 10 ** (precision+1));
// with rounding of last digit
uint _quotient = ((_numerator / denominator)) / 10;
return ( _quotient);
}
/**
* @dev wallet can receive funds.
*/
function () public payable {
emit Received(msg.sender, msg.value, address(this).balance);
}
/**
* @dev wallet can send funds
*/
function sendTo(address _payee, uint256 _amount) private {
require(_payee != 0 && _payee != address(this), "Burning tokens and self transfer not allowed");
require(_amount > 0, "Must transfer greater than zero");
_payee.transfer(_amount);
emit Sent(_payee, _amount, address(this).balance);
}
/**
* @dev function to see the balance of Ether in the wallet
*/
function balanceOf() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev function for the player to cash in tokens
*/
function redeemTokens(address _player, address _tokenAddress) public returns (bool success) {
require(acceptedToken(_tokenAddress), "Token must be a registered token");
require(block.timestamp >= closeDate, "Game must be closed");
require(gameDone == true, "Can't redeem tokens until results have been uploaded");
// instantiate a token contract instance from the deployed address
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
// check token allowance player has given to GameMaster contract
uint256 _allowedValue = _token.allowance(_player, address(this));
// transfer tokens to GameMaster
_token.transferFrom(_player, address(this), _allowedValue);
// check balance of tokens actually transfered
uint256 _transferedTokens = _allowedValue;
// calculate the percentage of the total token supply represented by the transfered tokens
uint256 _playerPercentage = percent(_transferedTokens, _token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[_tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
// pay out ETH to the player
sendTo(_player, _playerRewards);
// return that the function succeeded
return true;
}
// checks if a token is an accepted game token
function acceptedToken(address _tokenAddress) public view returns (bool) {
return movies[_tokenAddress].accepted;
}
/**
* @dev functions to calculate game results and payouts
*/
function calculateTokensIssued(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.totalSupply();
}
function closeToken(address _tokenAddress) private {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
_token.closeNow();
}
function calculateTokenRate(address _tokenAddress) private view returns (uint256) {
IPickFlixToken _token = IPickFlixToken(_tokenAddress);
return _token.rate();
}
// "15" in this function means 15%. Change that number to raise or lower
// the oracle fee.
function calculateOracleFee() private view returns (uint256) {
return balanceOf().mul(oracleFeePercent).div(100);
}
// this calculates how much Ether is available for player rewards
function calculateTotalPlayerRewards() private view returns (uint256) {
return balanceOf().sub(oracleFee);
}
// this calculates the total box office earnings of all movies in USD
function calculateTotalBoxOffice(uint256[] _boxOfficeTotals) private pure returns (uint256) {
uint256 _totalBoxOffice = 0;
for (uint256 i = 0; i < _boxOfficeTotals.length; i++) {
_totalBoxOffice = _totalBoxOffice.add(_boxOfficeTotals[i]);
}
return _totalBoxOffice;
}
// this calculates how much Ether to reward for each game token
function calculateTotalPlayerRewardsPerMovie(uint256 _boxOfficeTotal) public view returns (uint256) {
// 234 means 23.4%, using parts-per notation with three decimals of precision
uint256 _boxOfficePercentage = percent(_boxOfficeTotal, totalBoxOffice, 4);
// calculate the Ether rewards available for each movie
uint256 _rewards = totalPlayerRewards.mul(_boxOfficePercentage).div(10**4);
return _rewards;
}
function calculateRewardPerToken(uint256 _boxOfficeTotal, address tokenAddress) public view returns (uint256) {
IPickFlixToken token = IPickFlixToken(tokenAddress);
uint256 _playerBalance = token.balanceOf(msg.sender);
uint256 _playerPercentage = percent(_playerBalance, token.totalSupply(), 4);
// calculate the particular player's rewards, as a percentage of total player rewards for the movie
uint256 _playerRewards = movies[tokenAddress].totalPlayerRewards.mul(_playerPercentage).div(10**4);
return _playerRewards;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function calculateGameResults(address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
// check that there are as many box office totals as token addresses
require(_tokenAddresses.length == _boxOfficeTotals.length, "Must have box office results per token");
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
require(block.timestamp >= closeDate, "Game must have ended before results can be entered");
oracleFee = calculateOracleFee();
totalPlayerRewards = calculateTotalPlayerRewards();
totalBoxOffice = calculateTotalBoxOffice(_boxOfficeTotals);
// create Movies (see: Movie struct) and calculate player rewards
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
tokensIssued = tokensIssued.add(calculateTokensIssued(_tokenAddresses[i]));
movies[_tokenAddresses[i]] = Movie(_boxOfficeTotals[i], calculateTotalPlayerRewardsPerMovie(_boxOfficeTotals[i]), true);
}
// The owner will be the Factory that deploys this contract.
owner().transfer(oracleFee);
gameDone = true;
}
/**
* @dev add box office results and token addresses for the movies, and calculate game results
*/
function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
function killGame(address[] _tokenAddresses) public onlyOwner {
for (uint i = 0; i < _tokenAddresses.length; i++) {
IPickFlixToken token = IPickFlixToken(_tokenAddresses[i]);
require(token.balanceOf(this) == token.totalSupply());
token.kill();
}
selfdestruct(owner());
}
} | abortGame | function abortGame(address[] _tokenAddresses) public onlyOwner {
// calculate Oracle Fee and amount of Ether available for player rewards
require(gameDone == false, "Can only submit results once");
oracleFee = 0;
totalPlayerRewards = calculateTotalPlayerRewards();
closeDate = block.timestamp;
for (uint256 i = 0; i < _tokenAddresses.length; i++) {
uint tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
tokensIssued = tokensIssued.add(tokenSupply);
closeToken(_tokenAddresses[i]);
}
totalBoxOffice = tokensIssued;
// create Movies (see: Movie struct) and calculate player rewards
for (i = 0; i < _tokenAddresses.length; i++) {
tokenSupply = calculateTokensIssued(_tokenAddresses[i]);
movies[_tokenAddresses[i]] = Movie(tokenSupply, calculateTotalPlayerRewardsPerMovie(tokenSupply), true);
}
gameDone = true;
}
| /**
* @dev add box office results and token addresses for the movies, and calculate game results
*/ | NatSpecMultiLine | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
8156,
9080
]
} | 1,388 |
|||
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameFactory | contract PickflixGameFactory {
struct Game {
string gameName;
address gameMaster;
uint openDate;
uint closeDate;
}
// The list of all games this factory has created
Game[] public games;
// Each game master has a list of tokens
mapping(address => address[]) public gameTokens;
// The owner of the factory, i.e. GoBlock
address public owner;
// The address which will receive the oracle fee
address public oracleFeeReceiver;
// An event emitted when the oracle fee is received
event OraclePayoutReceived(uint value);
constructor() public {
owner = msg.sender;
oracleFeeReceiver = msg.sender;
}
function () public payable {
emit OraclePayoutReceived(msg.value);
}
// Throw an error if the sender is not the owner
modifier onlyOwner {
require(msg.sender == owner, "Only owner can execute this");
_;
}
// Create a new game master and add it to the factories game list
function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
// Create a token and associate it with a game
function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
// Upload the results for a game
function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
// Cancel a game and refund participants
function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
// Delete a game from the factory
function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
// Change the owner address
function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
// Change the address that receives the oracle fee
function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
// Send the ether to the oracle fee receiver
function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
} | //The contract in charge of creating games | LineComment | createGame | function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
| // Create a new game master and add it to the factories game list | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
989,
1374
]
} | 1,389 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameFactory | contract PickflixGameFactory {
struct Game {
string gameName;
address gameMaster;
uint openDate;
uint closeDate;
}
// The list of all games this factory has created
Game[] public games;
// Each game master has a list of tokens
mapping(address => address[]) public gameTokens;
// The owner of the factory, i.e. GoBlock
address public owner;
// The address which will receive the oracle fee
address public oracleFeeReceiver;
// An event emitted when the oracle fee is received
event OraclePayoutReceived(uint value);
constructor() public {
owner = msg.sender;
oracleFeeReceiver = msg.sender;
}
function () public payable {
emit OraclePayoutReceived(msg.value);
}
// Throw an error if the sender is not the owner
modifier onlyOwner {
require(msg.sender == owner, "Only owner can execute this");
_;
}
// Create a new game master and add it to the factories game list
function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
// Create a token and associate it with a game
function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
// Upload the results for a game
function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
// Cancel a game and refund participants
function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
// Delete a game from the factory
function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
// Change the owner address
function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
// Change the address that receives the oracle fee
function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
// Send the ether to the oracle fee receiver
function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
} | //The contract in charge of creating games | LineComment | createTokenForGame | function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
| // Create a token and associate it with a game | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1427,
1806
]
} | 1,390 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameFactory | contract PickflixGameFactory {
struct Game {
string gameName;
address gameMaster;
uint openDate;
uint closeDate;
}
// The list of all games this factory has created
Game[] public games;
// Each game master has a list of tokens
mapping(address => address[]) public gameTokens;
// The owner of the factory, i.e. GoBlock
address public owner;
// The address which will receive the oracle fee
address public oracleFeeReceiver;
// An event emitted when the oracle fee is received
event OraclePayoutReceived(uint value);
constructor() public {
owner = msg.sender;
oracleFeeReceiver = msg.sender;
}
function () public payable {
emit OraclePayoutReceived(msg.value);
}
// Throw an error if the sender is not the owner
modifier onlyOwner {
require(msg.sender == owner, "Only owner can execute this");
_;
}
// Create a new game master and add it to the factories game list
function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
// Create a token and associate it with a game
function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
// Upload the results for a game
function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
// Cancel a game and refund participants
function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
// Delete a game from the factory
function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
// Change the owner address
function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
// Change the address that receives the oracle fee
function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
// Send the ether to the oracle fee receiver
function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
} | //The contract in charge of creating games | LineComment | closeGame | function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
| // Upload the results for a game | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
1845,
2071
]
} | 1,391 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameFactory | contract PickflixGameFactory {
struct Game {
string gameName;
address gameMaster;
uint openDate;
uint closeDate;
}
// The list of all games this factory has created
Game[] public games;
// Each game master has a list of tokens
mapping(address => address[]) public gameTokens;
// The owner of the factory, i.e. GoBlock
address public owner;
// The address which will receive the oracle fee
address public oracleFeeReceiver;
// An event emitted when the oracle fee is received
event OraclePayoutReceived(uint value);
constructor() public {
owner = msg.sender;
oracleFeeReceiver = msg.sender;
}
function () public payable {
emit OraclePayoutReceived(msg.value);
}
// Throw an error if the sender is not the owner
modifier onlyOwner {
require(msg.sender == owner, "Only owner can execute this");
_;
}
// Create a new game master and add it to the factories game list
function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
// Create a token and associate it with a game
function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
// Upload the results for a game
function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
// Cancel a game and refund participants
function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
// Delete a game from the factory
function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
// Change the owner address
function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
// Change the address that receives the oracle fee
function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
// Send the ether to the oracle fee receiver
function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
} | //The contract in charge of creating games | LineComment | abortGame | function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
| // Cancel a game and refund participants | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2118,
2305
]
} | 1,392 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameFactory | contract PickflixGameFactory {
struct Game {
string gameName;
address gameMaster;
uint openDate;
uint closeDate;
}
// The list of all games this factory has created
Game[] public games;
// Each game master has a list of tokens
mapping(address => address[]) public gameTokens;
// The owner of the factory, i.e. GoBlock
address public owner;
// The address which will receive the oracle fee
address public oracleFeeReceiver;
// An event emitted when the oracle fee is received
event OraclePayoutReceived(uint value);
constructor() public {
owner = msg.sender;
oracleFeeReceiver = msg.sender;
}
function () public payable {
emit OraclePayoutReceived(msg.value);
}
// Throw an error if the sender is not the owner
modifier onlyOwner {
require(msg.sender == owner, "Only owner can execute this");
_;
}
// Create a new game master and add it to the factories game list
function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
// Create a token and associate it with a game
function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
// Upload the results for a game
function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
// Cancel a game and refund participants
function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
// Delete a game from the factory
function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
// Change the owner address
function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
// Change the address that receives the oracle fee
function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
// Send the ether to the oracle fee receiver
function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
} | //The contract in charge of creating games | LineComment | killGame | function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
| // Delete a game from the factory | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2345,
2633
]
} | 1,393 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameFactory | contract PickflixGameFactory {
struct Game {
string gameName;
address gameMaster;
uint openDate;
uint closeDate;
}
// The list of all games this factory has created
Game[] public games;
// Each game master has a list of tokens
mapping(address => address[]) public gameTokens;
// The owner of the factory, i.e. GoBlock
address public owner;
// The address which will receive the oracle fee
address public oracleFeeReceiver;
// An event emitted when the oracle fee is received
event OraclePayoutReceived(uint value);
constructor() public {
owner = msg.sender;
oracleFeeReceiver = msg.sender;
}
function () public payable {
emit OraclePayoutReceived(msg.value);
}
// Throw an error if the sender is not the owner
modifier onlyOwner {
require(msg.sender == owner, "Only owner can execute this");
_;
}
// Create a new game master and add it to the factories game list
function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
// Create a token and associate it with a game
function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
// Upload the results for a game
function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
// Cancel a game and refund participants
function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
// Delete a game from the factory
function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
// Change the owner address
function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
// Change the address that receives the oracle fee
function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
// Send the ether to the oracle fee receiver
function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
} | //The contract in charge of creating games | LineComment | setOwner | function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
| // Change the owner address | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2667,
2752
]
} | 1,394 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameFactory | contract PickflixGameFactory {
struct Game {
string gameName;
address gameMaster;
uint openDate;
uint closeDate;
}
// The list of all games this factory has created
Game[] public games;
// Each game master has a list of tokens
mapping(address => address[]) public gameTokens;
// The owner of the factory, i.e. GoBlock
address public owner;
// The address which will receive the oracle fee
address public oracleFeeReceiver;
// An event emitted when the oracle fee is received
event OraclePayoutReceived(uint value);
constructor() public {
owner = msg.sender;
oracleFeeReceiver = msg.sender;
}
function () public payable {
emit OraclePayoutReceived(msg.value);
}
// Throw an error if the sender is not the owner
modifier onlyOwner {
require(msg.sender == owner, "Only owner can execute this");
_;
}
// Create a new game master and add it to the factories game list
function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
// Create a token and associate it with a game
function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
// Upload the results for a game
function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
// Cancel a game and refund participants
function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
// Delete a game from the factory
function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
// Change the owner address
function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
// Change the address that receives the oracle fee
function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
// Send the ether to the oracle fee receiver
function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
} | //The contract in charge of creating games | LineComment | setOracleFeeReceiver | function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
| // Change the address that receives the oracle fee | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2809,
2924
]
} | 1,395 |
|
PickflixGameFactory | PickflixGameFactory.sol | 0x34f416364f52d6753aee14f2687726705039c2b5 | Solidity | PickflixGameFactory | contract PickflixGameFactory {
struct Game {
string gameName;
address gameMaster;
uint openDate;
uint closeDate;
}
// The list of all games this factory has created
Game[] public games;
// Each game master has a list of tokens
mapping(address => address[]) public gameTokens;
// The owner of the factory, i.e. GoBlock
address public owner;
// The address which will receive the oracle fee
address public oracleFeeReceiver;
// An event emitted when the oracle fee is received
event OraclePayoutReceived(uint value);
constructor() public {
owner = msg.sender;
oracleFeeReceiver = msg.sender;
}
function () public payable {
emit OraclePayoutReceived(msg.value);
}
// Throw an error if the sender is not the owner
modifier onlyOwner {
require(msg.sender == owner, "Only owner can execute this");
_;
}
// Create a new game master and add it to the factories game list
function createGame(string gameName, uint closeDate, uint oracleFeePercent) public onlyOwner returns (address){
address gameMaster = new PickflixGameMaster(gameName, closeDate, oracleFeePercent);
games.push(Game({
gameName: gameName,
gameMaster: gameMaster,
openDate: block.timestamp,
closeDate: closeDate
}));
return gameMaster;
}
// Create a token and associate it with a game
function createTokenForGame(uint gameIndex, string tokenName, string tokenSymbol, uint rate, string externalID) public onlyOwner returns (address) {
Game storage game = games[gameIndex];
address token = new PickFlixToken(tokenName, tokenSymbol, rate, game.gameMaster, game.closeDate, externalID);
gameTokens[game.gameMaster].push(token);
return token;
}
// Upload the results for a game
function closeGame(uint gameIndex, address[] _tokenAddresses, uint256[] _boxOfficeTotals) public onlyOwner {
PickflixGameMaster(games[gameIndex].gameMaster).calculateGameResults(_tokenAddresses, _boxOfficeTotals);
}
// Cancel a game and refund participants
function abortGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).abortGame(gameTokens[gameMaster]);
}
// Delete a game from the factory
function killGame(uint gameIndex) public onlyOwner {
address gameMaster = games[gameIndex].gameMaster;
PickflixGameMaster(gameMaster).killGame(gameTokens[gameMaster]);
games[gameIndex] = games[games.length-1];
delete games[games.length-1];
games.length--;
}
// Change the owner address
function setOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
// Change the address that receives the oracle fee
function setOracleFeeReceiver(address newReceiver) public onlyOwner {
oracleFeeReceiver = newReceiver;
}
// Send the ether to the oracle fee receiver
function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
} | //The contract in charge of creating games | LineComment | sendOraclePayout | function sendOraclePayout() public {
oracleFeeReceiver.transfer(address(this).balance);
}
| // Send the ether to the oracle fee receiver | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://36e2a22f770e0206c40641b4ed360d6ff14711c278ad13af9fd6179423f8784c | {
"func_code_index": [
2975,
3075
]
} | 1,396 |
|
MyFriendships | MyFriendships.sol | 0x1955a08c4f4e3edc8323b60f792ffc47141538a6 | Solidity | MyFriendships | contract MyFriendships {
address public me;
uint public numberOfFriends;
address public latestFriend;
mapping(address => bool) myFriends;
/**
* @dev Create a contract to keep track of my friendships.
*/
function MyFriendships() public {
me = msg.sender;
}
/**
* @dev Start an exciting new friendship with me.
*/
function becomeFriendsWithMe () public {
require(msg.sender != me); // I won't be friends with myself.
myFriends[msg.sender] = true;
latestFriend = msg.sender;
numberOfFriends++;
}
/**
* @dev Am I friends with this address?
*/
function friendsWith (address addr) public view returns (bool) {
return myFriends[addr];
}
} | /**
* @title MyFriendships
* @dev A contract for managing one's friendships.
*/ | NatSpecMultiLine | MyFriendships | function MyFriendships() public {
me = msg.sender;
}
| /**
* @dev Create a contract to keep track of my friendships.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://4c7a8b128bfb5b5cb2c734e9b275043fe415fae188a3a26cd19587e7847a411e | {
"func_code_index": [
247,
318
]
} | 1,397 |
|
MyFriendships | MyFriendships.sol | 0x1955a08c4f4e3edc8323b60f792ffc47141538a6 | Solidity | MyFriendships | contract MyFriendships {
address public me;
uint public numberOfFriends;
address public latestFriend;
mapping(address => bool) myFriends;
/**
* @dev Create a contract to keep track of my friendships.
*/
function MyFriendships() public {
me = msg.sender;
}
/**
* @dev Start an exciting new friendship with me.
*/
function becomeFriendsWithMe () public {
require(msg.sender != me); // I won't be friends with myself.
myFriends[msg.sender] = true;
latestFriend = msg.sender;
numberOfFriends++;
}
/**
* @dev Am I friends with this address?
*/
function friendsWith (address addr) public view returns (bool) {
return myFriends[addr];
}
} | /**
* @title MyFriendships
* @dev A contract for managing one's friendships.
*/ | NatSpecMultiLine | becomeFriendsWithMe | function becomeFriendsWithMe () public {
require(msg.sender != me); // I won't be friends with myself.
myFriends[msg.sender] = true;
latestFriend = msg.sender;
numberOfFriends++;
}
| /**
* @dev Start an exciting new friendship with me.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://4c7a8b128bfb5b5cb2c734e9b275043fe415fae188a3a26cd19587e7847a411e | {
"func_code_index": [
393,
619
]
} | 1,398 |
|
MyFriendships | MyFriendships.sol | 0x1955a08c4f4e3edc8323b60f792ffc47141538a6 | Solidity | MyFriendships | contract MyFriendships {
address public me;
uint public numberOfFriends;
address public latestFriend;
mapping(address => bool) myFriends;
/**
* @dev Create a contract to keep track of my friendships.
*/
function MyFriendships() public {
me = msg.sender;
}
/**
* @dev Start an exciting new friendship with me.
*/
function becomeFriendsWithMe () public {
require(msg.sender != me); // I won't be friends with myself.
myFriends[msg.sender] = true;
latestFriend = msg.sender;
numberOfFriends++;
}
/**
* @dev Am I friends with this address?
*/
function friendsWith (address addr) public view returns (bool) {
return myFriends[addr];
}
} | /**
* @title MyFriendships
* @dev A contract for managing one's friendships.
*/ | NatSpecMultiLine | friendsWith | function friendsWith (address addr) public view returns (bool) {
return myFriends[addr];
}
| /**
* @dev Am I friends with this address?
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | bzzr://4c7a8b128bfb5b5cb2c734e9b275043fe415fae188a3a26cd19587e7847a411e | {
"func_code_index": [
687,
796
]
} | 1,399 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.