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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Burner | Burner.sol | 0x0bf09916957f3eadc1be240c6f145fd7a34bf7f2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://a6415090acf70603bf5af800aa8c4494001140989736ae14d9b1eacb4a5a1d41 | {
"func_code_index": [
3721,
3922
]
} | 57,461 |
Burner | Burner.sol | 0x0bf09916957f3eadc1be240c6f145fd7a34bf7f2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://a6415090acf70603bf5af800aa8c4494001140989736ae14d9b1eacb4a5a1d41 | {
"func_code_index": [
4292,
4523
]
} | 57,462 |
Burner | Burner.sol | 0x0bf09916957f3eadc1be240c6f145fd7a34bf7f2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://a6415090acf70603bf5af800aa8c4494001140989736ae14d9b1eacb4a5a1d41 | {
"func_code_index": [
4774,
5095
]
} | 57,463 |
Burner | Burner.sol | 0x0bf09916957f3eadc1be240c6f145fd7a34bf7f2 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | owner | function owner() public view returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://a6415090acf70603bf5af800aa8c4494001140989736ae14d9b1eacb4a5a1d41 | {
"func_code_index": [
566,
650
]
} | 57,464 |
Burner | Burner.sol | 0x0bf09916957f3eadc1be240c6f145fd7a34bf7f2 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://a6415090acf70603bf5af800aa8c4494001140989736ae14d9b1eacb4a5a1d41 | {
"func_code_index": [
1209,
1362
]
} | 57,465 |
Burner | Burner.sol | 0x0bf09916957f3eadc1be240c6f145fd7a34bf7f2 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://a6415090acf70603bf5af800aa8c4494001140989736ae14d9b1eacb4a5a1d41 | {
"func_code_index": [
1512,
1761
]
} | 57,466 |
Burner | Burner.sol | 0x0bf09916957f3eadc1be240c6f145fd7a34bf7f2 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | lock | function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
| //Locks the contract for owner for the amount of time provided | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://a6415090acf70603bf5af800aa8c4494001140989736ae14d9b1eacb4a5a1d41 | {
"func_code_index": [
1929,
2148
]
} | 57,467 |
Burner | Burner.sol | 0x0bf09916957f3eadc1be240c6f145fd7a34bf7f2 | Solidity | Ownable | contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | unlock | function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
| //Unlocks the contract for owner when _lockTime is exceeds | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://a6415090acf70603bf5af800aa8c4494001140989736ae14d9b1eacb4a5a1d41 | {
"func_code_index": [
2219,
2517
]
} | 57,468 |
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
} | /**
* @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 {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
710,
891
]
} | 57,469 |
|
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
| /**
* @dev Allows the current owner to relinquish control of the contract.
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
983,
1100
]
} | 57,470 |
|
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
| /**
* @dev Multiplies two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
89,
266
]
} | 57,471 |
|
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
| /**
* @dev Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
350,
630
]
} | 57,472 |
|
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| /**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
744,
860
]
} | 57,473 |
|
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
924,
1054
]
} | 57,474 |
|
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | Pausable | contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
} | /**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/ | NatSpecMultiLine | pause | function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
| /**
* @dev called by the owner to pause, triggers stopped state
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
513,
609
]
} | 57,475 |
|
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | Pausable | contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
} | /**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/ | NatSpecMultiLine | unpause | function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
| /**
* @dev called by the owner to unpause, returns to normal state
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
693,
791
]
} | 57,476 |
|
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | name | function name() constant returns (string _name) {
return name;
}
| // Function to access name of token . | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
840,
917
]
} | 57,477 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | symbol | function symbol() constant returns (string _symbol) {
return symbol;
}
| // Function to access symbol of token . | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
961,
1044
]
} | 57,478 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | decimals | function decimals() constant returns (uint8 _decimals) {
return decimals;
}
| // Function to access decimals of token . | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
1090,
1178
]
} | 57,479 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | totalSupply | function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
| // Function to access total supply of tokens . | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
1229,
1328
]
} | 57,480 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | transfer | function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
| // Function that is called when a user or another contract wants to transfer funds . | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
1576,
2257
]
} | 57,481 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | transfer | function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
| // Function that is called when a user or another contract wants to transfer funds . | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
2350,
2731
]
} | 57,482 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | transfer | function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
| // Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons . | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
2862,
3381
]
} | 57,483 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | isContract | function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
| //assemble the given address bytecode. If bytecode exists then the _addr is a contract. | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
3473,
3753
]
} | 57,484 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | transferToAddress | function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
| //function that is called when transaction target is an address | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
3823,
4268
]
} | 57,485 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | transferToContract | function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
| //function that is called when transaction target is a contract | LineComment | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
4338,
4896
]
} | 57,486 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | approve | function approve(address _spender, uint256 _value)
public
whenNotPaused
returns (bool) {
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.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
5637,
5861
]
} | 57,487 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | allowance | function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
6185,
6350
]
} | 57,488 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | increaseApproval | function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
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.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
6816,
7134
]
} | 57,489 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | decreaseApproval | function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* @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.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
7605,
8067
]
} | 57,490 |
|||
WTO | WTO.sol | 0x9220895a55533a5e751d7d1b333bd74bdfc2c9aa | Solidity | WTO | contract WTO is Pausable {
using SafeMath for uint256;
mapping (address => uint) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
// Function to access name of token .
function name() constant returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() constant returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() constant returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() constant returns (uint256 _totalSupply) {
return totalSupply;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback)
whenNotPaused
returns (bool success)
{
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
require(balanceOf(msg.sender) >= _value);
balances[_to] = balanceOf(_to).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
assert(_to.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value)
whenNotPaused
returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(!frozenAccount[msg.sender]);
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(_to != address(0));
require(!frozenAccount[_to]);
require(balanceOf(msg.sender) >= _value);
require(!frozenAccount[msg.sender]);
balances[msg.sender] = balanceOf(msg.sender).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
/**
* @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
whenNotPaused
returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public returns (bool seccess) {
require(amount > 0);
require(addresses.length > 0);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = amount.mul(addresses.length);
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
balances[addresses[i]] = balances[addresses[i]].add(amount);
emit Transfer(msg.sender, addresses[i], amount, empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint256[] amounts) public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
require(!frozenAccount[msg.sender]);
uint256 totalAmount = 0;
for(uint i = 0; i < addresses.length; i++){
require(amounts[i] > 0);
require(addresses[i] != address(0));
require(!frozenAccount[addresses[i]]);
totalAmount = totalAmount.add(amounts[i]);
}
require(balances[msg.sender] >= totalAmount);
bytes memory empty;
for (i = 0; i < addresses.length; i++) {
balances[addresses[i]] = balances[addresses[i]].add(amounts[i]);
emit Transfer(msg.sender, addresses[i], amounts[i], empty);
}
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
return true;
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
} | collectTokens | function collectTokens(address[] addresses, uint256[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0);
require(addresses.length == amounts.length);
uint256 totalAmount = 0;
bytes memory empty;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0);
require(addresses[j] != address(0));
require(!frozenAccount[addresses[j]]);
require(balances[addresses[j]] >= amounts[j]);
balances[addresses[j]] = balances[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j], empty);
}
balances[msg.sender] = balances[msg.sender].add(totalAmount);
return true;
}
| /**
* @dev Function to collect tokens from the list of addresses
*/ | NatSpecMultiLine | v0.4.23+commit.124ca40d | bzzr://25025e3e18d4505e72e2e4bfba2aab8f2b15126ef2ffc076b781fab97cd44fd2 | {
"func_code_index": [
9734,
10599
]
} | 57,491 |
|||
BatchExchange | contracts/libraries/TokenConservation.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | TokenConservation | library TokenConservation {
using SignedSafeMath for int256;
/** @dev initialize the token conservation data structure
* @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked
*/
function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) {
return new int256[](tokenIdsForPrice.length + 1);
}
/** @dev returns the token imbalance of the fee token
* @param self internal datastructure created by TokenConservation.init()
*/
function feeTokenImbalance(int256[] memory self) internal pure returns (int256) {
return self[0];
}
/** @dev updated token conservation array.
* @param self internal datastructure created by TokenConservation.init()
* @param buyToken id of token whose imbalance should be subtracted from
* @param sellToken id of token whose imbalance should be added to
* @param tokenIdsForPrice sorted list of tokenIds
* @param buyAmount amount to be subtracted at `self[buyTokenIndex]`
* @param sellAmount amount to be added at `self[sellTokenIndex]`
*/
function updateTokenConservation(
int256[] memory self,
uint16 buyToken,
uint16 sellToken,
uint16[] memory tokenIdsForPrice,
uint128 buyAmount,
uint128 sellAmount
) internal pure {
uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice);
uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice);
self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount));
self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount));
}
/** @dev Ensures all array's elements are zero except the first.
* @param self internal datastructure created by TokenConservation.init()
* @return true if all, but first element of self are zero else false
*/
function checkTokenConservation(int256[] memory self) internal pure {
require(self[0] > 0, "Token conservation at 0 must be positive.");
for (uint256 i = 1; i < self.length; i++) {
require(self[i] == 0, "Token conservation does not hold");
}
}
/** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info.
* @param tokenIdsForPrice list of tokenIds
* @return true if tokenIdsForPrice is sorted else false
*/
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) {
for (uint256 i = 1; i < tokenIdsForPrice.length; i++) {
if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) {
return false;
}
}
return true;
}
/** @dev implementation of binary search on sorted list returns token id
* @param tokenId element whose index is to be found
* @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied.
* @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found).
*/
function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) {
// Fee token is not included in tokenIdsForPrice
if (tokenId == 0) {
return 0;
}
// binary search for the other tokens
uint256 leftValue = 0;
uint256 rightValue = tokenIdsForPrice.length - 1;
while (rightValue >= leftValue) {
uint256 middleValue = leftValue + (rightValue - leftValue) / 2;
if (tokenIdsForPrice[middleValue] == tokenId) {
// shifted one to the right to account for fee token at index 0
return middleValue + 1;
} else if (tokenIdsForPrice[middleValue] < tokenId) {
leftValue = middleValue + 1;
} else {
rightValue = middleValue - 1;
}
}
revert("Price not provided for token");
}
} | /** @title Token Conservation
* A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | init | function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) {
return new int256[](tokenIdsForPrice.length + 1);
}
| /** @dev initialize the token conservation data structure
* @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
246,
406
]
} | 57,492 |
BatchExchange | contracts/libraries/TokenConservation.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | TokenConservation | library TokenConservation {
using SignedSafeMath for int256;
/** @dev initialize the token conservation data structure
* @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked
*/
function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) {
return new int256[](tokenIdsForPrice.length + 1);
}
/** @dev returns the token imbalance of the fee token
* @param self internal datastructure created by TokenConservation.init()
*/
function feeTokenImbalance(int256[] memory self) internal pure returns (int256) {
return self[0];
}
/** @dev updated token conservation array.
* @param self internal datastructure created by TokenConservation.init()
* @param buyToken id of token whose imbalance should be subtracted from
* @param sellToken id of token whose imbalance should be added to
* @param tokenIdsForPrice sorted list of tokenIds
* @param buyAmount amount to be subtracted at `self[buyTokenIndex]`
* @param sellAmount amount to be added at `self[sellTokenIndex]`
*/
function updateTokenConservation(
int256[] memory self,
uint16 buyToken,
uint16 sellToken,
uint16[] memory tokenIdsForPrice,
uint128 buyAmount,
uint128 sellAmount
) internal pure {
uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice);
uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice);
self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount));
self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount));
}
/** @dev Ensures all array's elements are zero except the first.
* @param self internal datastructure created by TokenConservation.init()
* @return true if all, but first element of self are zero else false
*/
function checkTokenConservation(int256[] memory self) internal pure {
require(self[0] > 0, "Token conservation at 0 must be positive.");
for (uint256 i = 1; i < self.length; i++) {
require(self[i] == 0, "Token conservation does not hold");
}
}
/** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info.
* @param tokenIdsForPrice list of tokenIds
* @return true if tokenIdsForPrice is sorted else false
*/
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) {
for (uint256 i = 1; i < tokenIdsForPrice.length; i++) {
if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) {
return false;
}
}
return true;
}
/** @dev implementation of binary search on sorted list returns token id
* @param tokenId element whose index is to be found
* @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied.
* @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found).
*/
function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) {
// Fee token is not included in tokenIdsForPrice
if (tokenId == 0) {
return 0;
}
// binary search for the other tokens
uint256 leftValue = 0;
uint256 rightValue = tokenIdsForPrice.length - 1;
while (rightValue >= leftValue) {
uint256 middleValue = leftValue + (rightValue - leftValue) / 2;
if (tokenIdsForPrice[middleValue] == tokenId) {
// shifted one to the right to account for fee token at index 0
return middleValue + 1;
} else if (tokenIdsForPrice[middleValue] < tokenId) {
leftValue = middleValue + 1;
} else {
rightValue = middleValue - 1;
}
}
revert("Price not provided for token");
}
} | /** @title Token Conservation
* A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | feeTokenImbalance | function feeTokenImbalance(int256[] memory self) internal pure returns (int256) {
return self[0];
}
| /** @dev returns the token imbalance of the fee token
* @param self internal datastructure created by TokenConservation.init()
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
558,
676
]
} | 57,493 |
BatchExchange | contracts/libraries/TokenConservation.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | TokenConservation | library TokenConservation {
using SignedSafeMath for int256;
/** @dev initialize the token conservation data structure
* @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked
*/
function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) {
return new int256[](tokenIdsForPrice.length + 1);
}
/** @dev returns the token imbalance of the fee token
* @param self internal datastructure created by TokenConservation.init()
*/
function feeTokenImbalance(int256[] memory self) internal pure returns (int256) {
return self[0];
}
/** @dev updated token conservation array.
* @param self internal datastructure created by TokenConservation.init()
* @param buyToken id of token whose imbalance should be subtracted from
* @param sellToken id of token whose imbalance should be added to
* @param tokenIdsForPrice sorted list of tokenIds
* @param buyAmount amount to be subtracted at `self[buyTokenIndex]`
* @param sellAmount amount to be added at `self[sellTokenIndex]`
*/
function updateTokenConservation(
int256[] memory self,
uint16 buyToken,
uint16 sellToken,
uint16[] memory tokenIdsForPrice,
uint128 buyAmount,
uint128 sellAmount
) internal pure {
uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice);
uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice);
self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount));
self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount));
}
/** @dev Ensures all array's elements are zero except the first.
* @param self internal datastructure created by TokenConservation.init()
* @return true if all, but first element of self are zero else false
*/
function checkTokenConservation(int256[] memory self) internal pure {
require(self[0] > 0, "Token conservation at 0 must be positive.");
for (uint256 i = 1; i < self.length; i++) {
require(self[i] == 0, "Token conservation does not hold");
}
}
/** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info.
* @param tokenIdsForPrice list of tokenIds
* @return true if tokenIdsForPrice is sorted else false
*/
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) {
for (uint256 i = 1; i < tokenIdsForPrice.length; i++) {
if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) {
return false;
}
}
return true;
}
/** @dev implementation of binary search on sorted list returns token id
* @param tokenId element whose index is to be found
* @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied.
* @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found).
*/
function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) {
// Fee token is not included in tokenIdsForPrice
if (tokenId == 0) {
return 0;
}
// binary search for the other tokens
uint256 leftValue = 0;
uint256 rightValue = tokenIdsForPrice.length - 1;
while (rightValue >= leftValue) {
uint256 middleValue = leftValue + (rightValue - leftValue) / 2;
if (tokenIdsForPrice[middleValue] == tokenId) {
// shifted one to the right to account for fee token at index 0
return middleValue + 1;
} else if (tokenIdsForPrice[middleValue] < tokenId) {
leftValue = middleValue + 1;
} else {
rightValue = middleValue - 1;
}
}
revert("Price not provided for token");
}
} | /** @title Token Conservation
* A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | updateTokenConservation | function updateTokenConservation(
int256[] memory self,
uint16 buyToken,
uint16 sellToken,
uint16[] memory tokenIdsForPrice,
uint128 buyAmount,
uint128 sellAmount
) internal pure {
uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice);
uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice);
self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount));
self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount));
}
| /** @dev updated token conservation array.
* @param self internal datastructure created by TokenConservation.init()
* @param buyToken id of token whose imbalance should be subtracted from
* @param sellToken id of token whose imbalance should be added to
* @param tokenIdsForPrice sorted list of tokenIds
* @param buyAmount amount to be subtracted at `self[buyTokenIndex]`
* @param sellAmount amount to be added at `self[sellTokenIndex]`
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
1173,
1733
]
} | 57,494 |
BatchExchange | contracts/libraries/TokenConservation.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | TokenConservation | library TokenConservation {
using SignedSafeMath for int256;
/** @dev initialize the token conservation data structure
* @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked
*/
function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) {
return new int256[](tokenIdsForPrice.length + 1);
}
/** @dev returns the token imbalance of the fee token
* @param self internal datastructure created by TokenConservation.init()
*/
function feeTokenImbalance(int256[] memory self) internal pure returns (int256) {
return self[0];
}
/** @dev updated token conservation array.
* @param self internal datastructure created by TokenConservation.init()
* @param buyToken id of token whose imbalance should be subtracted from
* @param sellToken id of token whose imbalance should be added to
* @param tokenIdsForPrice sorted list of tokenIds
* @param buyAmount amount to be subtracted at `self[buyTokenIndex]`
* @param sellAmount amount to be added at `self[sellTokenIndex]`
*/
function updateTokenConservation(
int256[] memory self,
uint16 buyToken,
uint16 sellToken,
uint16[] memory tokenIdsForPrice,
uint128 buyAmount,
uint128 sellAmount
) internal pure {
uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice);
uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice);
self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount));
self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount));
}
/** @dev Ensures all array's elements are zero except the first.
* @param self internal datastructure created by TokenConservation.init()
* @return true if all, but first element of self are zero else false
*/
function checkTokenConservation(int256[] memory self) internal pure {
require(self[0] > 0, "Token conservation at 0 must be positive.");
for (uint256 i = 1; i < self.length; i++) {
require(self[i] == 0, "Token conservation does not hold");
}
}
/** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info.
* @param tokenIdsForPrice list of tokenIds
* @return true if tokenIdsForPrice is sorted else false
*/
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) {
for (uint256 i = 1; i < tokenIdsForPrice.length; i++) {
if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) {
return false;
}
}
return true;
}
/** @dev implementation of binary search on sorted list returns token id
* @param tokenId element whose index is to be found
* @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied.
* @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found).
*/
function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) {
// Fee token is not included in tokenIdsForPrice
if (tokenId == 0) {
return 0;
}
// binary search for the other tokens
uint256 leftValue = 0;
uint256 rightValue = tokenIdsForPrice.length - 1;
while (rightValue >= leftValue) {
uint256 middleValue = leftValue + (rightValue - leftValue) / 2;
if (tokenIdsForPrice[middleValue] == tokenId) {
// shifted one to the right to account for fee token at index 0
return middleValue + 1;
} else if (tokenIdsForPrice[middleValue] < tokenId) {
leftValue = middleValue + 1;
} else {
rightValue = middleValue - 1;
}
}
revert("Price not provided for token");
}
} | /** @title Token Conservation
* A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | checkTokenConservation | function checkTokenConservation(int256[] memory self) internal pure {
require(self[0] > 0, "Token conservation at 0 must be positive.");
for (uint256 i = 1; i < self.length; i++) {
require(self[i] == 0, "Token conservation does not hold");
}
}
| /** @dev Ensures all array's elements are zero except the first.
* @param self internal datastructure created by TokenConservation.init()
* @return true if all, but first element of self are zero else false
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
1972,
2265
]
} | 57,495 |
BatchExchange | contracts/libraries/TokenConservation.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | TokenConservation | library TokenConservation {
using SignedSafeMath for int256;
/** @dev initialize the token conservation data structure
* @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked
*/
function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) {
return new int256[](tokenIdsForPrice.length + 1);
}
/** @dev returns the token imbalance of the fee token
* @param self internal datastructure created by TokenConservation.init()
*/
function feeTokenImbalance(int256[] memory self) internal pure returns (int256) {
return self[0];
}
/** @dev updated token conservation array.
* @param self internal datastructure created by TokenConservation.init()
* @param buyToken id of token whose imbalance should be subtracted from
* @param sellToken id of token whose imbalance should be added to
* @param tokenIdsForPrice sorted list of tokenIds
* @param buyAmount amount to be subtracted at `self[buyTokenIndex]`
* @param sellAmount amount to be added at `self[sellTokenIndex]`
*/
function updateTokenConservation(
int256[] memory self,
uint16 buyToken,
uint16 sellToken,
uint16[] memory tokenIdsForPrice,
uint128 buyAmount,
uint128 sellAmount
) internal pure {
uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice);
uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice);
self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount));
self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount));
}
/** @dev Ensures all array's elements are zero except the first.
* @param self internal datastructure created by TokenConservation.init()
* @return true if all, but first element of self are zero else false
*/
function checkTokenConservation(int256[] memory self) internal pure {
require(self[0] > 0, "Token conservation at 0 must be positive.");
for (uint256 i = 1; i < self.length; i++) {
require(self[i] == 0, "Token conservation does not hold");
}
}
/** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info.
* @param tokenIdsForPrice list of tokenIds
* @return true if tokenIdsForPrice is sorted else false
*/
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) {
for (uint256 i = 1; i < tokenIdsForPrice.length; i++) {
if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) {
return false;
}
}
return true;
}
/** @dev implementation of binary search on sorted list returns token id
* @param tokenId element whose index is to be found
* @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied.
* @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found).
*/
function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) {
// Fee token is not included in tokenIdsForPrice
if (tokenId == 0) {
return 0;
}
// binary search for the other tokens
uint256 leftValue = 0;
uint256 rightValue = tokenIdsForPrice.length - 1;
while (rightValue >= leftValue) {
uint256 middleValue = leftValue + (rightValue - leftValue) / 2;
if (tokenIdsForPrice[middleValue] == tokenId) {
// shifted one to the right to account for fee token at index 0
return middleValue + 1;
} else if (tokenIdsForPrice[middleValue] < tokenId) {
leftValue = middleValue + 1;
} else {
rightValue = middleValue - 1;
}
}
revert("Price not provided for token");
}
} | /** @title Token Conservation
* A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | checkPriceOrdering | function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) {
for (uint256 i = 1; i < tokenIdsForPrice.length; i++) {
if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) {
return false;
}
}
return true;
}
| /** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info.
* @param tokenIdsForPrice list of tokenIds
* @return true if tokenIdsForPrice is sorted else false
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
2511,
2826
]
} | 57,496 |
BatchExchange | contracts/libraries/TokenConservation.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | TokenConservation | library TokenConservation {
using SignedSafeMath for int256;
/** @dev initialize the token conservation data structure
* @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked
*/
function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) {
return new int256[](tokenIdsForPrice.length + 1);
}
/** @dev returns the token imbalance of the fee token
* @param self internal datastructure created by TokenConservation.init()
*/
function feeTokenImbalance(int256[] memory self) internal pure returns (int256) {
return self[0];
}
/** @dev updated token conservation array.
* @param self internal datastructure created by TokenConservation.init()
* @param buyToken id of token whose imbalance should be subtracted from
* @param sellToken id of token whose imbalance should be added to
* @param tokenIdsForPrice sorted list of tokenIds
* @param buyAmount amount to be subtracted at `self[buyTokenIndex]`
* @param sellAmount amount to be added at `self[sellTokenIndex]`
*/
function updateTokenConservation(
int256[] memory self,
uint16 buyToken,
uint16 sellToken,
uint16[] memory tokenIdsForPrice,
uint128 buyAmount,
uint128 sellAmount
) internal pure {
uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice);
uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice);
self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount));
self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount));
}
/** @dev Ensures all array's elements are zero except the first.
* @param self internal datastructure created by TokenConservation.init()
* @return true if all, but first element of self are zero else false
*/
function checkTokenConservation(int256[] memory self) internal pure {
require(self[0] > 0, "Token conservation at 0 must be positive.");
for (uint256 i = 1; i < self.length; i++) {
require(self[i] == 0, "Token conservation does not hold");
}
}
/** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info.
* @param tokenIdsForPrice list of tokenIds
* @return true if tokenIdsForPrice is sorted else false
*/
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) {
for (uint256 i = 1; i < tokenIdsForPrice.length; i++) {
if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) {
return false;
}
}
return true;
}
/** @dev implementation of binary search on sorted list returns token id
* @param tokenId element whose index is to be found
* @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied.
* @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found).
*/
function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) {
// Fee token is not included in tokenIdsForPrice
if (tokenId == 0) {
return 0;
}
// binary search for the other tokens
uint256 leftValue = 0;
uint256 rightValue = tokenIdsForPrice.length - 1;
while (rightValue >= leftValue) {
uint256 middleValue = leftValue + (rightValue - leftValue) / 2;
if (tokenIdsForPrice[middleValue] == tokenId) {
// shifted one to the right to account for fee token at index 0
return middleValue + 1;
} else if (tokenIdsForPrice[middleValue] < tokenId) {
leftValue = middleValue + 1;
} else {
rightValue = middleValue - 1;
}
}
revert("Price not provided for token");
}
} | /** @title Token Conservation
* A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | findPriceIndex | function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) {
// Fee token is not included in tokenIdsForPrice
if (tokenId == 0) {
return 0;
}
// binary search for the other tokens
uint256 leftValue = 0;
uint256 rightValue = tokenIdsForPrice.length - 1;
while (rightValue >= leftValue) {
uint256 middleValue = leftValue + (rightValue - leftValue) / 2;
if (tokenIdsForPrice[middleValue] == tokenId) {
// shifted one to the right to account for fee token at index 0
return middleValue + 1;
} else if (tokenIdsForPrice[middleValue] < tokenId) {
leftValue = middleValue + 1;
} else {
rightValue = middleValue - 1;
}
}
revert("Price not provided for token");
}
| /** @dev implementation of binary search on sorted list returns token id
* @param tokenId element whose index is to be found
* @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied.
* @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found).
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
3166,
4103
]
} | 57,497 |
Commune | Commune.sol | 0x4f7892978a0eea4ce75b9b8ccefffa542cc4d40e | Solidity | Commune | contract Commune is ICommune {
using SafeMath for uint256;
struct aCommune {
bool allowsJoining;
bool allowsRemoving;
bool allowsOutsideContribution;
address asset;
uint256 proratedTotal;
uint256 memberCount;
address controller;
string uri;
}
mapping (uint256 => aCommune) public getCommune;
// maybe we should rather use
// mapping (address => EnumerableSet.UintSet) private _holderTokens;
// like https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol#L33
mapping (uint256 => mapping(address => bool)) private _isCommuneMember;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _balanceAtJoin;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _spentBalance;
// in basis points, 0 through 500, i.e. max take 5%
uint256 private _feeRate = 100;
// where fee goes to
address private _treasuryAddress;
// for creating new commune IDs
uint256 private _nonce;
// can update treasury address and fee rate
address private _controllerAddress;
// Getters ///
function numberOfCommunes() external override view returns (uint256){
return _nonce;
}
function isCommuneMember(uint256 commune, address account) external communeExists(commune) override view returns (bool){
return _isCommuneMember[commune][account];
}
function feeRate() external override view returns (uint256){
return _feeRate;
}
function treasuryAddress() external override view returns (address){
return _treasuryAddress;
}
function controller() external override view returns (address){
return _controllerAddress;
}
// modifiers
modifier controllerOnly(){
require(msg.sender == _controllerAddress, "Commune: only contract controller can do this");
_;
}
modifier communeControllerOnly(uint256 commune){
require(getCommune[commune].controller == msg.sender, "Commune: only the commune controller can do this");
_;
}
modifier communeExists(uint256 commune){
require(commune <= _nonce, "Commune: commune does not exists");
_;
}
function contribute(uint256 amount, uint256 commune) external communeExists(commune) override {
require(_isCommuneMember[commune][msg.sender] || getCommune[commune].allowsOutsideContribution, "Commune: Must be a member to contribute");
require(getCommune[commune].memberCount > 0, "Commune: commune has no members, cannot accept contributions");
address assetAddress = getCommune[commune].asset;
IERC20 asset = IERC20(assetAddress);
uint256 fee = amount
.mul(_feeRate)
.div(10000);
uint256 amountToCommune = amount
.sub(fee)
.div(getCommune[commune].memberCount);
asset.transferFrom(msg.sender, address(this), amountToCommune);
asset.transferFrom(msg.sender, _treasuryAddress, fee);
getCommune[commune].proratedTotal = getCommune[commune].proratedTotal.add(amountToCommune);
emit Contribute(msg.sender, commune, amount);
}
/**
@dev _uri should link to a JSON file of the form
{
"title": "Commune Title",
"description": "Commune description"
}
*/
function createCommune(string memory _uri, address asset, bool allowJoining, bool allowRemoving, bool allowOutsideContribution) external override returns(uint256 _id) {
require((!allowJoining && allowRemoving) || (allowJoining && !allowRemoving) || (!allowJoining && !allowRemoving), "Commune: cannot both allow joining and removing");
_id = ++_nonce;
getCommune[_id].controller = msg.sender;
getCommune[_id].allowsJoining = allowJoining;
getCommune[_id].allowsRemoving = allowRemoving;
getCommune[_id].allowsOutsideContribution = allowOutsideContribution;
getCommune[_id].asset = asset;
getCommune[_id].uri = _uri;
emit URI(_uri, _id);
}
//Join/Add Functions
function joinCommune(uint256 commune) external override {
require(getCommune[commune].allowsJoining, "Commune: commune does not allow joining");
_addCommuneMember(msg.sender, commune);
}
function addCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
_addCommuneMember(account, commune);
}
function _addCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(!_isCommuneMember[commune][account], "Commune: account is already in commune");
_isCommuneMember[commune][account] = true;
++getCommune[commune].memberCount;
_balanceAtJoin[commune][account] = getCommune[commune].proratedTotal;
emit AddCommuneMember(account, commune);
}
// Leave/Remove Functions
function leaveCommune(uint256 commune) external override {
_removeCommuneMember(msg.sender, commune);
}
function removeCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
require(getCommune[commune].allowsRemoving, "Commune: commune does not allow removing");
_removeCommuneMember(account, commune);
}
function _removeCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(_isCommuneMember[commune][account], "Commune: account is not in commune");
_isCommuneMember[commune][account] = false;
getCommune[commune].memberCount = getCommune[commune].memberCount.sub(1);
// we reset the spent balance, incase they'e added back later, to prevent a negative number
_spentBalance[commune][account] = 0;
emit RemoveCommuneMember(account, commune);
}
constructor(address _controller) {
_setURI("your-uri-here");
_controllerAddress = _controller;
_treasuryAddress = _controller;
}
/// controller functions ///
function updateCommuneController(address account, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].controller = account;
emit UpdateCommuneController(account, commune);
}
function updateCommuneURI(string memory _uri, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].uri = _uri;
emit URI(_uri, commune);
}
function updateController(address account) external controllerOnly override {
_controllerAddress = account;
emit UpdateController(account);
}
function updateFee(uint256 rate) external controllerOnly override {
// max fee is 5%
require(rate <= 500 && rate >= 0, "Commune: fee rate must be between 0 and 500");
_feeRate = rate;
emit UpdateFee(rate);
}
function setTreasuryAddress(address newTreasury) external controllerOnly override {
_treasuryAddress = newTreasury;
emit UpdateTreasuryAddress(newTreasury);
}
// boiler, mostly ripped from ERC1155 then modified
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
function uri(uint256 commune) communeExists(commune) external view returns (string memory) {
string memory _communeURI = getCommune[commune].uri;
// if the commune URI is set, return it. Note, might still need to replace `\{id\}`
if (bytes(_communeURI).length > 0) {
return _communeURI;
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return _uri;
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function balanceOf(address account, uint256 commune) public view virtual override returns (uint256) {
require(account != address(0), "Commune: balance query for the zero address");
if(!_isCommuneMember[commune][account]){
return 0;
}
return getCommune[commune].proratedTotal
.sub(_balanceAtJoin[commune][account])
.sub(_spentBalance[commune][account]);
}
/**
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "Commune: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "Commune: batch balance query for the zero address");
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
function setApprovalForAll(address operator, bool approved) public virtual {
require(msg.sender != operator, "Commune: setting approval status for self");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address account, address operator) public view returns (bool) {
return _operatorApprovals[account][operator];
}
function withdraw(address account, address to, uint256 commune, uint256 amount) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
balanceOf(account, commune).sub(amount, "Commune: withdraw amount exceeds balance");
_spentBalance[commune][account] = _spentBalance[commune][account].add(amount);
IERC20(getCommune[commune].asset).transfer(to, amount);
emit Withdraw(operator, account, to, commune, amount);
}
function withdrawBatch(address account, address to, uint256[] memory communes, uint256[] memory amounts) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
for (uint i = 0; i < communes.length; i++) {
balanceOf(account, communes[i]).sub(amounts[i], "Commune: withdraw amount exceeds balance");
_spentBalance[communes[i]][account] = _spentBalance[communes[i]][account].add(amounts[i]);
IERC20(getCommune[communes[i]].asset).transfer(to, amounts[i]);
}
emit WithdrawBatch(operator, account, to, communes, amounts);
}
} | numberOfCommunes | function numberOfCommunes() external override view returns (uint256){
return _nonce;
}
| // Getters /// | LineComment | v0.7.3+commit.9bfce1f6 | MIT | ipfs://b94e99684d24b8c95813b89bd6a236b00bcbd816e2a127637e8d07dfbf17d216 | {
"func_code_index": [
1247,
1349
]
} | 57,498 |
||
Commune | Commune.sol | 0x4f7892978a0eea4ce75b9b8ccefffa542cc4d40e | Solidity | Commune | contract Commune is ICommune {
using SafeMath for uint256;
struct aCommune {
bool allowsJoining;
bool allowsRemoving;
bool allowsOutsideContribution;
address asset;
uint256 proratedTotal;
uint256 memberCount;
address controller;
string uri;
}
mapping (uint256 => aCommune) public getCommune;
// maybe we should rather use
// mapping (address => EnumerableSet.UintSet) private _holderTokens;
// like https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol#L33
mapping (uint256 => mapping(address => bool)) private _isCommuneMember;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _balanceAtJoin;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _spentBalance;
// in basis points, 0 through 500, i.e. max take 5%
uint256 private _feeRate = 100;
// where fee goes to
address private _treasuryAddress;
// for creating new commune IDs
uint256 private _nonce;
// can update treasury address and fee rate
address private _controllerAddress;
// Getters ///
function numberOfCommunes() external override view returns (uint256){
return _nonce;
}
function isCommuneMember(uint256 commune, address account) external communeExists(commune) override view returns (bool){
return _isCommuneMember[commune][account];
}
function feeRate() external override view returns (uint256){
return _feeRate;
}
function treasuryAddress() external override view returns (address){
return _treasuryAddress;
}
function controller() external override view returns (address){
return _controllerAddress;
}
// modifiers
modifier controllerOnly(){
require(msg.sender == _controllerAddress, "Commune: only contract controller can do this");
_;
}
modifier communeControllerOnly(uint256 commune){
require(getCommune[commune].controller == msg.sender, "Commune: only the commune controller can do this");
_;
}
modifier communeExists(uint256 commune){
require(commune <= _nonce, "Commune: commune does not exists");
_;
}
function contribute(uint256 amount, uint256 commune) external communeExists(commune) override {
require(_isCommuneMember[commune][msg.sender] || getCommune[commune].allowsOutsideContribution, "Commune: Must be a member to contribute");
require(getCommune[commune].memberCount > 0, "Commune: commune has no members, cannot accept contributions");
address assetAddress = getCommune[commune].asset;
IERC20 asset = IERC20(assetAddress);
uint256 fee = amount
.mul(_feeRate)
.div(10000);
uint256 amountToCommune = amount
.sub(fee)
.div(getCommune[commune].memberCount);
asset.transferFrom(msg.sender, address(this), amountToCommune);
asset.transferFrom(msg.sender, _treasuryAddress, fee);
getCommune[commune].proratedTotal = getCommune[commune].proratedTotal.add(amountToCommune);
emit Contribute(msg.sender, commune, amount);
}
/**
@dev _uri should link to a JSON file of the form
{
"title": "Commune Title",
"description": "Commune description"
}
*/
function createCommune(string memory _uri, address asset, bool allowJoining, bool allowRemoving, bool allowOutsideContribution) external override returns(uint256 _id) {
require((!allowJoining && allowRemoving) || (allowJoining && !allowRemoving) || (!allowJoining && !allowRemoving), "Commune: cannot both allow joining and removing");
_id = ++_nonce;
getCommune[_id].controller = msg.sender;
getCommune[_id].allowsJoining = allowJoining;
getCommune[_id].allowsRemoving = allowRemoving;
getCommune[_id].allowsOutsideContribution = allowOutsideContribution;
getCommune[_id].asset = asset;
getCommune[_id].uri = _uri;
emit URI(_uri, _id);
}
//Join/Add Functions
function joinCommune(uint256 commune) external override {
require(getCommune[commune].allowsJoining, "Commune: commune does not allow joining");
_addCommuneMember(msg.sender, commune);
}
function addCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
_addCommuneMember(account, commune);
}
function _addCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(!_isCommuneMember[commune][account], "Commune: account is already in commune");
_isCommuneMember[commune][account] = true;
++getCommune[commune].memberCount;
_balanceAtJoin[commune][account] = getCommune[commune].proratedTotal;
emit AddCommuneMember(account, commune);
}
// Leave/Remove Functions
function leaveCommune(uint256 commune) external override {
_removeCommuneMember(msg.sender, commune);
}
function removeCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
require(getCommune[commune].allowsRemoving, "Commune: commune does not allow removing");
_removeCommuneMember(account, commune);
}
function _removeCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(_isCommuneMember[commune][account], "Commune: account is not in commune");
_isCommuneMember[commune][account] = false;
getCommune[commune].memberCount = getCommune[commune].memberCount.sub(1);
// we reset the spent balance, incase they'e added back later, to prevent a negative number
_spentBalance[commune][account] = 0;
emit RemoveCommuneMember(account, commune);
}
constructor(address _controller) {
_setURI("your-uri-here");
_controllerAddress = _controller;
_treasuryAddress = _controller;
}
/// controller functions ///
function updateCommuneController(address account, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].controller = account;
emit UpdateCommuneController(account, commune);
}
function updateCommuneURI(string memory _uri, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].uri = _uri;
emit URI(_uri, commune);
}
function updateController(address account) external controllerOnly override {
_controllerAddress = account;
emit UpdateController(account);
}
function updateFee(uint256 rate) external controllerOnly override {
// max fee is 5%
require(rate <= 500 && rate >= 0, "Commune: fee rate must be between 0 and 500");
_feeRate = rate;
emit UpdateFee(rate);
}
function setTreasuryAddress(address newTreasury) external controllerOnly override {
_treasuryAddress = newTreasury;
emit UpdateTreasuryAddress(newTreasury);
}
// boiler, mostly ripped from ERC1155 then modified
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
function uri(uint256 commune) communeExists(commune) external view returns (string memory) {
string memory _communeURI = getCommune[commune].uri;
// if the commune URI is set, return it. Note, might still need to replace `\{id\}`
if (bytes(_communeURI).length > 0) {
return _communeURI;
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return _uri;
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function balanceOf(address account, uint256 commune) public view virtual override returns (uint256) {
require(account != address(0), "Commune: balance query for the zero address");
if(!_isCommuneMember[commune][account]){
return 0;
}
return getCommune[commune].proratedTotal
.sub(_balanceAtJoin[commune][account])
.sub(_spentBalance[commune][account]);
}
/**
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "Commune: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "Commune: batch balance query for the zero address");
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
function setApprovalForAll(address operator, bool approved) public virtual {
require(msg.sender != operator, "Commune: setting approval status for self");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address account, address operator) public view returns (bool) {
return _operatorApprovals[account][operator];
}
function withdraw(address account, address to, uint256 commune, uint256 amount) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
balanceOf(account, commune).sub(amount, "Commune: withdraw amount exceeds balance");
_spentBalance[commune][account] = _spentBalance[commune][account].add(amount);
IERC20(getCommune[commune].asset).transfer(to, amount);
emit Withdraw(operator, account, to, commune, amount);
}
function withdrawBatch(address account, address to, uint256[] memory communes, uint256[] memory amounts) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
for (uint i = 0; i < communes.length; i++) {
balanceOf(account, communes[i]).sub(amounts[i], "Commune: withdraw amount exceeds balance");
_spentBalance[communes[i]][account] = _spentBalance[communes[i]][account].add(amounts[i]);
IERC20(getCommune[communes[i]].asset).transfer(to, amounts[i]);
}
emit WithdrawBatch(operator, account, to, communes, amounts);
}
} | createCommune | function createCommune(string memory _uri, address asset, bool allowJoining, bool allowRemoving, bool allowOutsideContribution) external override returns(uint256 _id) {
require((!allowJoining && allowRemoving) || (allowJoining && !allowRemoving) || (!allowJoining && !allowRemoving), "Commune: cannot both allow joining and removing");
_id = ++_nonce;
getCommune[_id].controller = msg.sender;
getCommune[_id].allowsJoining = allowJoining;
getCommune[_id].allowsRemoving = allowRemoving;
getCommune[_id].allowsOutsideContribution = allowOutsideContribution;
getCommune[_id].asset = asset;
getCommune[_id].uri = _uri;
emit URI(_uri, _id);
}
| /**
@dev _uri should link to a JSON file of the form
{
"title": "Commune Title",
"description": "Commune description"
}
*/ | NatSpecMultiLine | v0.7.3+commit.9bfce1f6 | MIT | ipfs://b94e99684d24b8c95813b89bd6a236b00bcbd816e2a127637e8d07dfbf17d216 | {
"func_code_index": [
3502,
4225
]
} | 57,499 |
||
Commune | Commune.sol | 0x4f7892978a0eea4ce75b9b8ccefffa542cc4d40e | Solidity | Commune | contract Commune is ICommune {
using SafeMath for uint256;
struct aCommune {
bool allowsJoining;
bool allowsRemoving;
bool allowsOutsideContribution;
address asset;
uint256 proratedTotal;
uint256 memberCount;
address controller;
string uri;
}
mapping (uint256 => aCommune) public getCommune;
// maybe we should rather use
// mapping (address => EnumerableSet.UintSet) private _holderTokens;
// like https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol#L33
mapping (uint256 => mapping(address => bool)) private _isCommuneMember;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _balanceAtJoin;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _spentBalance;
// in basis points, 0 through 500, i.e. max take 5%
uint256 private _feeRate = 100;
// where fee goes to
address private _treasuryAddress;
// for creating new commune IDs
uint256 private _nonce;
// can update treasury address and fee rate
address private _controllerAddress;
// Getters ///
function numberOfCommunes() external override view returns (uint256){
return _nonce;
}
function isCommuneMember(uint256 commune, address account) external communeExists(commune) override view returns (bool){
return _isCommuneMember[commune][account];
}
function feeRate() external override view returns (uint256){
return _feeRate;
}
function treasuryAddress() external override view returns (address){
return _treasuryAddress;
}
function controller() external override view returns (address){
return _controllerAddress;
}
// modifiers
modifier controllerOnly(){
require(msg.sender == _controllerAddress, "Commune: only contract controller can do this");
_;
}
modifier communeControllerOnly(uint256 commune){
require(getCommune[commune].controller == msg.sender, "Commune: only the commune controller can do this");
_;
}
modifier communeExists(uint256 commune){
require(commune <= _nonce, "Commune: commune does not exists");
_;
}
function contribute(uint256 amount, uint256 commune) external communeExists(commune) override {
require(_isCommuneMember[commune][msg.sender] || getCommune[commune].allowsOutsideContribution, "Commune: Must be a member to contribute");
require(getCommune[commune].memberCount > 0, "Commune: commune has no members, cannot accept contributions");
address assetAddress = getCommune[commune].asset;
IERC20 asset = IERC20(assetAddress);
uint256 fee = amount
.mul(_feeRate)
.div(10000);
uint256 amountToCommune = amount
.sub(fee)
.div(getCommune[commune].memberCount);
asset.transferFrom(msg.sender, address(this), amountToCommune);
asset.transferFrom(msg.sender, _treasuryAddress, fee);
getCommune[commune].proratedTotal = getCommune[commune].proratedTotal.add(amountToCommune);
emit Contribute(msg.sender, commune, amount);
}
/**
@dev _uri should link to a JSON file of the form
{
"title": "Commune Title",
"description": "Commune description"
}
*/
function createCommune(string memory _uri, address asset, bool allowJoining, bool allowRemoving, bool allowOutsideContribution) external override returns(uint256 _id) {
require((!allowJoining && allowRemoving) || (allowJoining && !allowRemoving) || (!allowJoining && !allowRemoving), "Commune: cannot both allow joining and removing");
_id = ++_nonce;
getCommune[_id].controller = msg.sender;
getCommune[_id].allowsJoining = allowJoining;
getCommune[_id].allowsRemoving = allowRemoving;
getCommune[_id].allowsOutsideContribution = allowOutsideContribution;
getCommune[_id].asset = asset;
getCommune[_id].uri = _uri;
emit URI(_uri, _id);
}
//Join/Add Functions
function joinCommune(uint256 commune) external override {
require(getCommune[commune].allowsJoining, "Commune: commune does not allow joining");
_addCommuneMember(msg.sender, commune);
}
function addCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
_addCommuneMember(account, commune);
}
function _addCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(!_isCommuneMember[commune][account], "Commune: account is already in commune");
_isCommuneMember[commune][account] = true;
++getCommune[commune].memberCount;
_balanceAtJoin[commune][account] = getCommune[commune].proratedTotal;
emit AddCommuneMember(account, commune);
}
// Leave/Remove Functions
function leaveCommune(uint256 commune) external override {
_removeCommuneMember(msg.sender, commune);
}
function removeCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
require(getCommune[commune].allowsRemoving, "Commune: commune does not allow removing");
_removeCommuneMember(account, commune);
}
function _removeCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(_isCommuneMember[commune][account], "Commune: account is not in commune");
_isCommuneMember[commune][account] = false;
getCommune[commune].memberCount = getCommune[commune].memberCount.sub(1);
// we reset the spent balance, incase they'e added back later, to prevent a negative number
_spentBalance[commune][account] = 0;
emit RemoveCommuneMember(account, commune);
}
constructor(address _controller) {
_setURI("your-uri-here");
_controllerAddress = _controller;
_treasuryAddress = _controller;
}
/// controller functions ///
function updateCommuneController(address account, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].controller = account;
emit UpdateCommuneController(account, commune);
}
function updateCommuneURI(string memory _uri, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].uri = _uri;
emit URI(_uri, commune);
}
function updateController(address account) external controllerOnly override {
_controllerAddress = account;
emit UpdateController(account);
}
function updateFee(uint256 rate) external controllerOnly override {
// max fee is 5%
require(rate <= 500 && rate >= 0, "Commune: fee rate must be between 0 and 500");
_feeRate = rate;
emit UpdateFee(rate);
}
function setTreasuryAddress(address newTreasury) external controllerOnly override {
_treasuryAddress = newTreasury;
emit UpdateTreasuryAddress(newTreasury);
}
// boiler, mostly ripped from ERC1155 then modified
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
function uri(uint256 commune) communeExists(commune) external view returns (string memory) {
string memory _communeURI = getCommune[commune].uri;
// if the commune URI is set, return it. Note, might still need to replace `\{id\}`
if (bytes(_communeURI).length > 0) {
return _communeURI;
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return _uri;
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function balanceOf(address account, uint256 commune) public view virtual override returns (uint256) {
require(account != address(0), "Commune: balance query for the zero address");
if(!_isCommuneMember[commune][account]){
return 0;
}
return getCommune[commune].proratedTotal
.sub(_balanceAtJoin[commune][account])
.sub(_spentBalance[commune][account]);
}
/**
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "Commune: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "Commune: batch balance query for the zero address");
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
function setApprovalForAll(address operator, bool approved) public virtual {
require(msg.sender != operator, "Commune: setting approval status for self");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address account, address operator) public view returns (bool) {
return _operatorApprovals[account][operator];
}
function withdraw(address account, address to, uint256 commune, uint256 amount) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
balanceOf(account, commune).sub(amount, "Commune: withdraw amount exceeds balance");
_spentBalance[commune][account] = _spentBalance[commune][account].add(amount);
IERC20(getCommune[commune].asset).transfer(to, amount);
emit Withdraw(operator, account, to, commune, amount);
}
function withdrawBatch(address account, address to, uint256[] memory communes, uint256[] memory amounts) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
for (uint i = 0; i < communes.length; i++) {
balanceOf(account, communes[i]).sub(amounts[i], "Commune: withdraw amount exceeds balance");
_spentBalance[communes[i]][account] = _spentBalance[communes[i]][account].add(amounts[i]);
IERC20(getCommune[communes[i]].asset).transfer(to, amounts[i]);
}
emit WithdrawBatch(operator, account, to, communes, amounts);
}
} | joinCommune | function joinCommune(uint256 commune) external override {
require(getCommune[commune].allowsJoining, "Commune: commune does not allow joining");
_addCommuneMember(msg.sender, commune);
}
| //Join/Add Functions | LineComment | v0.7.3+commit.9bfce1f6 | MIT | ipfs://b94e99684d24b8c95813b89bd6a236b00bcbd816e2a127637e8d07dfbf17d216 | {
"func_code_index": [
4252,
4462
]
} | 57,500 |
||
Commune | Commune.sol | 0x4f7892978a0eea4ce75b9b8ccefffa542cc4d40e | Solidity | Commune | contract Commune is ICommune {
using SafeMath for uint256;
struct aCommune {
bool allowsJoining;
bool allowsRemoving;
bool allowsOutsideContribution;
address asset;
uint256 proratedTotal;
uint256 memberCount;
address controller;
string uri;
}
mapping (uint256 => aCommune) public getCommune;
// maybe we should rather use
// mapping (address => EnumerableSet.UintSet) private _holderTokens;
// like https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol#L33
mapping (uint256 => mapping(address => bool)) private _isCommuneMember;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _balanceAtJoin;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _spentBalance;
// in basis points, 0 through 500, i.e. max take 5%
uint256 private _feeRate = 100;
// where fee goes to
address private _treasuryAddress;
// for creating new commune IDs
uint256 private _nonce;
// can update treasury address and fee rate
address private _controllerAddress;
// Getters ///
function numberOfCommunes() external override view returns (uint256){
return _nonce;
}
function isCommuneMember(uint256 commune, address account) external communeExists(commune) override view returns (bool){
return _isCommuneMember[commune][account];
}
function feeRate() external override view returns (uint256){
return _feeRate;
}
function treasuryAddress() external override view returns (address){
return _treasuryAddress;
}
function controller() external override view returns (address){
return _controllerAddress;
}
// modifiers
modifier controllerOnly(){
require(msg.sender == _controllerAddress, "Commune: only contract controller can do this");
_;
}
modifier communeControllerOnly(uint256 commune){
require(getCommune[commune].controller == msg.sender, "Commune: only the commune controller can do this");
_;
}
modifier communeExists(uint256 commune){
require(commune <= _nonce, "Commune: commune does not exists");
_;
}
function contribute(uint256 amount, uint256 commune) external communeExists(commune) override {
require(_isCommuneMember[commune][msg.sender] || getCommune[commune].allowsOutsideContribution, "Commune: Must be a member to contribute");
require(getCommune[commune].memberCount > 0, "Commune: commune has no members, cannot accept contributions");
address assetAddress = getCommune[commune].asset;
IERC20 asset = IERC20(assetAddress);
uint256 fee = amount
.mul(_feeRate)
.div(10000);
uint256 amountToCommune = amount
.sub(fee)
.div(getCommune[commune].memberCount);
asset.transferFrom(msg.sender, address(this), amountToCommune);
asset.transferFrom(msg.sender, _treasuryAddress, fee);
getCommune[commune].proratedTotal = getCommune[commune].proratedTotal.add(amountToCommune);
emit Contribute(msg.sender, commune, amount);
}
/**
@dev _uri should link to a JSON file of the form
{
"title": "Commune Title",
"description": "Commune description"
}
*/
function createCommune(string memory _uri, address asset, bool allowJoining, bool allowRemoving, bool allowOutsideContribution) external override returns(uint256 _id) {
require((!allowJoining && allowRemoving) || (allowJoining && !allowRemoving) || (!allowJoining && !allowRemoving), "Commune: cannot both allow joining and removing");
_id = ++_nonce;
getCommune[_id].controller = msg.sender;
getCommune[_id].allowsJoining = allowJoining;
getCommune[_id].allowsRemoving = allowRemoving;
getCommune[_id].allowsOutsideContribution = allowOutsideContribution;
getCommune[_id].asset = asset;
getCommune[_id].uri = _uri;
emit URI(_uri, _id);
}
//Join/Add Functions
function joinCommune(uint256 commune) external override {
require(getCommune[commune].allowsJoining, "Commune: commune does not allow joining");
_addCommuneMember(msg.sender, commune);
}
function addCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
_addCommuneMember(account, commune);
}
function _addCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(!_isCommuneMember[commune][account], "Commune: account is already in commune");
_isCommuneMember[commune][account] = true;
++getCommune[commune].memberCount;
_balanceAtJoin[commune][account] = getCommune[commune].proratedTotal;
emit AddCommuneMember(account, commune);
}
// Leave/Remove Functions
function leaveCommune(uint256 commune) external override {
_removeCommuneMember(msg.sender, commune);
}
function removeCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
require(getCommune[commune].allowsRemoving, "Commune: commune does not allow removing");
_removeCommuneMember(account, commune);
}
function _removeCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(_isCommuneMember[commune][account], "Commune: account is not in commune");
_isCommuneMember[commune][account] = false;
getCommune[commune].memberCount = getCommune[commune].memberCount.sub(1);
// we reset the spent balance, incase they'e added back later, to prevent a negative number
_spentBalance[commune][account] = 0;
emit RemoveCommuneMember(account, commune);
}
constructor(address _controller) {
_setURI("your-uri-here");
_controllerAddress = _controller;
_treasuryAddress = _controller;
}
/// controller functions ///
function updateCommuneController(address account, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].controller = account;
emit UpdateCommuneController(account, commune);
}
function updateCommuneURI(string memory _uri, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].uri = _uri;
emit URI(_uri, commune);
}
function updateController(address account) external controllerOnly override {
_controllerAddress = account;
emit UpdateController(account);
}
function updateFee(uint256 rate) external controllerOnly override {
// max fee is 5%
require(rate <= 500 && rate >= 0, "Commune: fee rate must be between 0 and 500");
_feeRate = rate;
emit UpdateFee(rate);
}
function setTreasuryAddress(address newTreasury) external controllerOnly override {
_treasuryAddress = newTreasury;
emit UpdateTreasuryAddress(newTreasury);
}
// boiler, mostly ripped from ERC1155 then modified
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
function uri(uint256 commune) communeExists(commune) external view returns (string memory) {
string memory _communeURI = getCommune[commune].uri;
// if the commune URI is set, return it. Note, might still need to replace `\{id\}`
if (bytes(_communeURI).length > 0) {
return _communeURI;
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return _uri;
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function balanceOf(address account, uint256 commune) public view virtual override returns (uint256) {
require(account != address(0), "Commune: balance query for the zero address");
if(!_isCommuneMember[commune][account]){
return 0;
}
return getCommune[commune].proratedTotal
.sub(_balanceAtJoin[commune][account])
.sub(_spentBalance[commune][account]);
}
/**
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "Commune: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "Commune: batch balance query for the zero address");
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
function setApprovalForAll(address operator, bool approved) public virtual {
require(msg.sender != operator, "Commune: setting approval status for self");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address account, address operator) public view returns (bool) {
return _operatorApprovals[account][operator];
}
function withdraw(address account, address to, uint256 commune, uint256 amount) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
balanceOf(account, commune).sub(amount, "Commune: withdraw amount exceeds balance");
_spentBalance[commune][account] = _spentBalance[commune][account].add(amount);
IERC20(getCommune[commune].asset).transfer(to, amount);
emit Withdraw(operator, account, to, commune, amount);
}
function withdrawBatch(address account, address to, uint256[] memory communes, uint256[] memory amounts) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
for (uint i = 0; i < communes.length; i++) {
balanceOf(account, communes[i]).sub(amounts[i], "Commune: withdraw amount exceeds balance");
_spentBalance[communes[i]][account] = _spentBalance[communes[i]][account].add(amounts[i]);
IERC20(getCommune[communes[i]].asset).transfer(to, amounts[i]);
}
emit WithdrawBatch(operator, account, to, communes, amounts);
}
} | leaveCommune | function leaveCommune(uint256 commune) external override {
_removeCommuneMember(msg.sender, commune);
}
| // Leave/Remove Functions | LineComment | v0.7.3+commit.9bfce1f6 | MIT | ipfs://b94e99684d24b8c95813b89bd6a236b00bcbd816e2a127637e8d07dfbf17d216 | {
"func_code_index": [
5086,
5205
]
} | 57,501 |
||
Commune | Commune.sol | 0x4f7892978a0eea4ce75b9b8ccefffa542cc4d40e | Solidity | Commune | contract Commune is ICommune {
using SafeMath for uint256;
struct aCommune {
bool allowsJoining;
bool allowsRemoving;
bool allowsOutsideContribution;
address asset;
uint256 proratedTotal;
uint256 memberCount;
address controller;
string uri;
}
mapping (uint256 => aCommune) public getCommune;
// maybe we should rather use
// mapping (address => EnumerableSet.UintSet) private _holderTokens;
// like https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol#L33
mapping (uint256 => mapping(address => bool)) private _isCommuneMember;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _balanceAtJoin;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _spentBalance;
// in basis points, 0 through 500, i.e. max take 5%
uint256 private _feeRate = 100;
// where fee goes to
address private _treasuryAddress;
// for creating new commune IDs
uint256 private _nonce;
// can update treasury address and fee rate
address private _controllerAddress;
// Getters ///
function numberOfCommunes() external override view returns (uint256){
return _nonce;
}
function isCommuneMember(uint256 commune, address account) external communeExists(commune) override view returns (bool){
return _isCommuneMember[commune][account];
}
function feeRate() external override view returns (uint256){
return _feeRate;
}
function treasuryAddress() external override view returns (address){
return _treasuryAddress;
}
function controller() external override view returns (address){
return _controllerAddress;
}
// modifiers
modifier controllerOnly(){
require(msg.sender == _controllerAddress, "Commune: only contract controller can do this");
_;
}
modifier communeControllerOnly(uint256 commune){
require(getCommune[commune].controller == msg.sender, "Commune: only the commune controller can do this");
_;
}
modifier communeExists(uint256 commune){
require(commune <= _nonce, "Commune: commune does not exists");
_;
}
function contribute(uint256 amount, uint256 commune) external communeExists(commune) override {
require(_isCommuneMember[commune][msg.sender] || getCommune[commune].allowsOutsideContribution, "Commune: Must be a member to contribute");
require(getCommune[commune].memberCount > 0, "Commune: commune has no members, cannot accept contributions");
address assetAddress = getCommune[commune].asset;
IERC20 asset = IERC20(assetAddress);
uint256 fee = amount
.mul(_feeRate)
.div(10000);
uint256 amountToCommune = amount
.sub(fee)
.div(getCommune[commune].memberCount);
asset.transferFrom(msg.sender, address(this), amountToCommune);
asset.transferFrom(msg.sender, _treasuryAddress, fee);
getCommune[commune].proratedTotal = getCommune[commune].proratedTotal.add(amountToCommune);
emit Contribute(msg.sender, commune, amount);
}
/**
@dev _uri should link to a JSON file of the form
{
"title": "Commune Title",
"description": "Commune description"
}
*/
function createCommune(string memory _uri, address asset, bool allowJoining, bool allowRemoving, bool allowOutsideContribution) external override returns(uint256 _id) {
require((!allowJoining && allowRemoving) || (allowJoining && !allowRemoving) || (!allowJoining && !allowRemoving), "Commune: cannot both allow joining and removing");
_id = ++_nonce;
getCommune[_id].controller = msg.sender;
getCommune[_id].allowsJoining = allowJoining;
getCommune[_id].allowsRemoving = allowRemoving;
getCommune[_id].allowsOutsideContribution = allowOutsideContribution;
getCommune[_id].asset = asset;
getCommune[_id].uri = _uri;
emit URI(_uri, _id);
}
//Join/Add Functions
function joinCommune(uint256 commune) external override {
require(getCommune[commune].allowsJoining, "Commune: commune does not allow joining");
_addCommuneMember(msg.sender, commune);
}
function addCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
_addCommuneMember(account, commune);
}
function _addCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(!_isCommuneMember[commune][account], "Commune: account is already in commune");
_isCommuneMember[commune][account] = true;
++getCommune[commune].memberCount;
_balanceAtJoin[commune][account] = getCommune[commune].proratedTotal;
emit AddCommuneMember(account, commune);
}
// Leave/Remove Functions
function leaveCommune(uint256 commune) external override {
_removeCommuneMember(msg.sender, commune);
}
function removeCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
require(getCommune[commune].allowsRemoving, "Commune: commune does not allow removing");
_removeCommuneMember(account, commune);
}
function _removeCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(_isCommuneMember[commune][account], "Commune: account is not in commune");
_isCommuneMember[commune][account] = false;
getCommune[commune].memberCount = getCommune[commune].memberCount.sub(1);
// we reset the spent balance, incase they'e added back later, to prevent a negative number
_spentBalance[commune][account] = 0;
emit RemoveCommuneMember(account, commune);
}
constructor(address _controller) {
_setURI("your-uri-here");
_controllerAddress = _controller;
_treasuryAddress = _controller;
}
/// controller functions ///
function updateCommuneController(address account, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].controller = account;
emit UpdateCommuneController(account, commune);
}
function updateCommuneURI(string memory _uri, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].uri = _uri;
emit URI(_uri, commune);
}
function updateController(address account) external controllerOnly override {
_controllerAddress = account;
emit UpdateController(account);
}
function updateFee(uint256 rate) external controllerOnly override {
// max fee is 5%
require(rate <= 500 && rate >= 0, "Commune: fee rate must be between 0 and 500");
_feeRate = rate;
emit UpdateFee(rate);
}
function setTreasuryAddress(address newTreasury) external controllerOnly override {
_treasuryAddress = newTreasury;
emit UpdateTreasuryAddress(newTreasury);
}
// boiler, mostly ripped from ERC1155 then modified
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
function uri(uint256 commune) communeExists(commune) external view returns (string memory) {
string memory _communeURI = getCommune[commune].uri;
// if the commune URI is set, return it. Note, might still need to replace `\{id\}`
if (bytes(_communeURI).length > 0) {
return _communeURI;
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return _uri;
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function balanceOf(address account, uint256 commune) public view virtual override returns (uint256) {
require(account != address(0), "Commune: balance query for the zero address");
if(!_isCommuneMember[commune][account]){
return 0;
}
return getCommune[commune].proratedTotal
.sub(_balanceAtJoin[commune][account])
.sub(_spentBalance[commune][account]);
}
/**
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "Commune: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "Commune: batch balance query for the zero address");
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
function setApprovalForAll(address operator, bool approved) public virtual {
require(msg.sender != operator, "Commune: setting approval status for self");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address account, address operator) public view returns (bool) {
return _operatorApprovals[account][operator];
}
function withdraw(address account, address to, uint256 commune, uint256 amount) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
balanceOf(account, commune).sub(amount, "Commune: withdraw amount exceeds balance");
_spentBalance[commune][account] = _spentBalance[commune][account].add(amount);
IERC20(getCommune[commune].asset).transfer(to, amount);
emit Withdraw(operator, account, to, commune, amount);
}
function withdrawBatch(address account, address to, uint256[] memory communes, uint256[] memory amounts) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
for (uint i = 0; i < communes.length; i++) {
balanceOf(account, communes[i]).sub(amounts[i], "Commune: withdraw amount exceeds balance");
_spentBalance[communes[i]][account] = _spentBalance[communes[i]][account].add(amounts[i]);
IERC20(getCommune[communes[i]].asset).transfer(to, amounts[i]);
}
emit WithdrawBatch(operator, account, to, communes, amounts);
}
} | updateCommuneController | function updateCommuneController(address account, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].controller = account;
emit UpdateCommuneController(account, commune);
}
| /// controller functions /// | NatSpecSingleLine | v0.7.3+commit.9bfce1f6 | MIT | ipfs://b94e99684d24b8c95813b89bd6a236b00bcbd816e2a127637e8d07dfbf17d216 | {
"func_code_index": [
6211,
6445
]
} | 57,502 |
||
Commune | Commune.sol | 0x4f7892978a0eea4ce75b9b8ccefffa542cc4d40e | Solidity | Commune | contract Commune is ICommune {
using SafeMath for uint256;
struct aCommune {
bool allowsJoining;
bool allowsRemoving;
bool allowsOutsideContribution;
address asset;
uint256 proratedTotal;
uint256 memberCount;
address controller;
string uri;
}
mapping (uint256 => aCommune) public getCommune;
// maybe we should rather use
// mapping (address => EnumerableSet.UintSet) private _holderTokens;
// like https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol#L33
mapping (uint256 => mapping(address => bool)) private _isCommuneMember;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _balanceAtJoin;
// commune -> address -> balance
mapping (uint256 => mapping (address => uint256)) private _spentBalance;
// in basis points, 0 through 500, i.e. max take 5%
uint256 private _feeRate = 100;
// where fee goes to
address private _treasuryAddress;
// for creating new commune IDs
uint256 private _nonce;
// can update treasury address and fee rate
address private _controllerAddress;
// Getters ///
function numberOfCommunes() external override view returns (uint256){
return _nonce;
}
function isCommuneMember(uint256 commune, address account) external communeExists(commune) override view returns (bool){
return _isCommuneMember[commune][account];
}
function feeRate() external override view returns (uint256){
return _feeRate;
}
function treasuryAddress() external override view returns (address){
return _treasuryAddress;
}
function controller() external override view returns (address){
return _controllerAddress;
}
// modifiers
modifier controllerOnly(){
require(msg.sender == _controllerAddress, "Commune: only contract controller can do this");
_;
}
modifier communeControllerOnly(uint256 commune){
require(getCommune[commune].controller == msg.sender, "Commune: only the commune controller can do this");
_;
}
modifier communeExists(uint256 commune){
require(commune <= _nonce, "Commune: commune does not exists");
_;
}
function contribute(uint256 amount, uint256 commune) external communeExists(commune) override {
require(_isCommuneMember[commune][msg.sender] || getCommune[commune].allowsOutsideContribution, "Commune: Must be a member to contribute");
require(getCommune[commune].memberCount > 0, "Commune: commune has no members, cannot accept contributions");
address assetAddress = getCommune[commune].asset;
IERC20 asset = IERC20(assetAddress);
uint256 fee = amount
.mul(_feeRate)
.div(10000);
uint256 amountToCommune = amount
.sub(fee)
.div(getCommune[commune].memberCount);
asset.transferFrom(msg.sender, address(this), amountToCommune);
asset.transferFrom(msg.sender, _treasuryAddress, fee);
getCommune[commune].proratedTotal = getCommune[commune].proratedTotal.add(amountToCommune);
emit Contribute(msg.sender, commune, amount);
}
/**
@dev _uri should link to a JSON file of the form
{
"title": "Commune Title",
"description": "Commune description"
}
*/
function createCommune(string memory _uri, address asset, bool allowJoining, bool allowRemoving, bool allowOutsideContribution) external override returns(uint256 _id) {
require((!allowJoining && allowRemoving) || (allowJoining && !allowRemoving) || (!allowJoining && !allowRemoving), "Commune: cannot both allow joining and removing");
_id = ++_nonce;
getCommune[_id].controller = msg.sender;
getCommune[_id].allowsJoining = allowJoining;
getCommune[_id].allowsRemoving = allowRemoving;
getCommune[_id].allowsOutsideContribution = allowOutsideContribution;
getCommune[_id].asset = asset;
getCommune[_id].uri = _uri;
emit URI(_uri, _id);
}
//Join/Add Functions
function joinCommune(uint256 commune) external override {
require(getCommune[commune].allowsJoining, "Commune: commune does not allow joining");
_addCommuneMember(msg.sender, commune);
}
function addCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
_addCommuneMember(account, commune);
}
function _addCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(!_isCommuneMember[commune][account], "Commune: account is already in commune");
_isCommuneMember[commune][account] = true;
++getCommune[commune].memberCount;
_balanceAtJoin[commune][account] = getCommune[commune].proratedTotal;
emit AddCommuneMember(account, commune);
}
// Leave/Remove Functions
function leaveCommune(uint256 commune) external override {
_removeCommuneMember(msg.sender, commune);
}
function removeCommuneMember(address account, uint256 commune) external communeControllerOnly(commune) override {
require(getCommune[commune].allowsRemoving, "Commune: commune does not allow removing");
_removeCommuneMember(account, commune);
}
function _removeCommuneMember(address account, uint256 commune) private communeExists(commune) {
require(_isCommuneMember[commune][account], "Commune: account is not in commune");
_isCommuneMember[commune][account] = false;
getCommune[commune].memberCount = getCommune[commune].memberCount.sub(1);
// we reset the spent balance, incase they'e added back later, to prevent a negative number
_spentBalance[commune][account] = 0;
emit RemoveCommuneMember(account, commune);
}
constructor(address _controller) {
_setURI("your-uri-here");
_controllerAddress = _controller;
_treasuryAddress = _controller;
}
/// controller functions ///
function updateCommuneController(address account, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].controller = account;
emit UpdateCommuneController(account, commune);
}
function updateCommuneURI(string memory _uri, uint256 commune) external communeControllerOnly(commune) override {
getCommune[commune].uri = _uri;
emit URI(_uri, commune);
}
function updateController(address account) external controllerOnly override {
_controllerAddress = account;
emit UpdateController(account);
}
function updateFee(uint256 rate) external controllerOnly override {
// max fee is 5%
require(rate <= 500 && rate >= 0, "Commune: fee rate must be between 0 and 500");
_feeRate = rate;
emit UpdateFee(rate);
}
function setTreasuryAddress(address newTreasury) external controllerOnly override {
_treasuryAddress = newTreasury;
emit UpdateTreasuryAddress(newTreasury);
}
// boiler, mostly ripped from ERC1155 then modified
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
function uri(uint256 commune) communeExists(commune) external view returns (string memory) {
string memory _communeURI = getCommune[commune].uri;
// if the commune URI is set, return it. Note, might still need to replace `\{id\}`
if (bytes(_communeURI).length > 0) {
return _communeURI;
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return _uri;
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
function balanceOf(address account, uint256 commune) public view virtual override returns (uint256) {
require(account != address(0), "Commune: balance query for the zero address");
if(!_isCommuneMember[commune][account]){
return 0;
}
return getCommune[commune].proratedTotal
.sub(_balanceAtJoin[commune][account])
.sub(_spentBalance[commune][account]);
}
/**
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "Commune: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "Commune: batch balance query for the zero address");
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
function setApprovalForAll(address operator, bool approved) public virtual {
require(msg.sender != operator, "Commune: setting approval status for self");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address account, address operator) public view returns (bool) {
return _operatorApprovals[account][operator];
}
function withdraw(address account, address to, uint256 commune, uint256 amount) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
balanceOf(account, commune).sub(amount, "Commune: withdraw amount exceeds balance");
_spentBalance[commune][account] = _spentBalance[commune][account].add(amount);
IERC20(getCommune[commune].asset).transfer(to, amount);
emit Withdraw(operator, account, to, commune, amount);
}
function withdrawBatch(address account, address to, uint256[] memory communes, uint256[] memory amounts) public override {
require(to != address(0), "Commune: Cannot withdraw to the zero address");
require(
account == msg.sender || isApprovedForAll(account, msg.sender),
"Commune: Caller is not owner nor approved"
);
address operator = msg.sender;
for (uint i = 0; i < communes.length; i++) {
balanceOf(account, communes[i]).sub(amounts[i], "Commune: withdraw amount exceeds balance");
_spentBalance[communes[i]][account] = _spentBalance[communes[i]][account].add(amounts[i]);
IERC20(getCommune[communes[i]].asset).transfer(to, amounts[i]);
}
emit WithdrawBatch(operator, account, to, communes, amounts);
}
} | balanceOfBatch | function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "Commune: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
require(accounts[i] != address(0), "Commune: batch balance query for the zero address");
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
| /**
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/ | NatSpecMultiLine | v0.7.3+commit.9bfce1f6 | MIT | ipfs://b94e99684d24b8c95813b89bd6a236b00bcbd816e2a127637e8d07dfbf17d216 | {
"func_code_index": [
8557,
9176
]
} | 57,503 |
||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
| /**
* @dev Multiplies two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
89,
272
]
} | 57,504 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
356,
629
]
} | 57,505 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| /**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
744,
860
]
} | 57,506 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
924,
1060
]
} | 57,507 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | setOwner | function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
| // contract owner | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
1880,
1964
]
} | 57,508 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | setCharity | function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
| // Set charity address | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
1993,
2106
]
} | 57,509 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | setItemRegistry | function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
| // Set item registry | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
2133,
2260
]
} | 57,510 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | addAdmin | function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
| // Add admin | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
2279,
2370
]
} | 57,511 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | removeAdmin | function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
| // Remove admin | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
2392,
2486
]
} | 57,512 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | enableERC721 | function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
| // Unlocks ERC721 behaviour, allowing for trading on third party platforms. | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
2568,
2648
]
} | 57,513 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | withdrawAll | function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
| // Withdraw | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
2666,
2762
]
} | 57,514 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | populateFromItemRegistry | function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
| // Listing | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
2882,
3219
]
} | 57,515 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | calculateNextPrice | function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
| // Buy | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
4581,
5057
]
} | 57,516 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | calculateDevCut | function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
| // Dev cut | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
5074,
5569
]
} | 57,517 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | buy | function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
| // Buy function | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
5591,
8048
]
} | 57,518 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | balanceOf | function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
| // balance of an address | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
8470,
8745
]
} | 57,519 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | ownerOf | function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
| // owner of token | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
8769,
8884
]
} | 57,520 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | tokensOf | function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
| // tokens of an address | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
8914,
9310
]
} | 57,521 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | tokenExists | function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
| // token exists | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
9332,
9449
]
} | 57,522 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | approvedFor | function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
| // approved for | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
9471,
9595
]
} | 57,523 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | approve | function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
| // approve | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
9612,
10074
]
} | 57,524 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | isAdmin | function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
| // read | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
10785,
10892
]
} | 57,525 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | ownerkill | function ownerkill() public onlyOwner {
selfdestruct(owner);
}
| // selfdestruct | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
11994,
12071
]
} | 57,526 |
|||
ItemToken | ItemToken.sol | 0x7e0f4a1d28228cdc3079bca1e1668fb18ddbc995 | Solidity | ItemToken | contract ItemToken {
using SafeMath for uint256; // Loading the SafeMath library
// Events of the contract
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner; // owner of the contract
address private charityAddress; // address of the charity
mapping (address => bool) private admins; // admins of the contract
IItemRegistry private itemRegistry; // Item registry
bool private erc721Enabled = false;
// limits for devcut
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
uint256[] private listedItems; // array of items
mapping (uint256 => address) private ownerOfItem; // owner of the item
mapping (uint256 => uint256) private startingPriceOfItem; // starting price of the item
mapping (uint256 => uint256) private previousPriceOfItem; // previous price of the item
mapping (uint256 => uint256) private priceOfItem; // actual price of the item
mapping (uint256 => uint256) private charityCutOfItem; // charity cut of the item
mapping (uint256 => address) private approvedOfItem; // item is approved for this address
// constructor
constructor() public {
owner = msg.sender;
admins[owner] = true;
}
// modifiers
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
modifier onlyERC721() {
require(erc721Enabled);
_;
}
// contract owner
function setOwner (address _owner) onlyOwner() public {
owner = _owner;
}
// Set charity address
function setCharity (address _charityAddress) onlyOwner() public {
charityAddress = _charityAddress;
}
// Set item registry
function setItemRegistry (address _itemRegistry) onlyOwner() public {
itemRegistry = IItemRegistry(_itemRegistry);
}
// Add admin
function addAdmin (address _admin) onlyOwner() public {
admins[_admin] = true;
}
// Remove admin
function removeAdmin (address _admin) onlyOwner() public {
delete admins[_admin];
}
// Unlocks ERC721 behaviour, allowing for trading on third party platforms.
function enableERC721 () onlyOwner() public {
erc721Enabled = true;
}
// Withdraw
function withdrawAll () onlyOwner() public {
owner.transfer(address(this).balance);
}
function withdrawAmount (uint256 _amount) onlyOwner() public {
owner.transfer(_amount);
}
// Listing
function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (charityCutOfItem[_itemIds[i]] > 0 || priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
}
function listItemFromRegistry (uint256 _itemId) onlyOwner() public {
require(itemRegistry != address(0));
require(itemRegistry.ownerOf(_itemId) != address(0));
require(itemRegistry.priceOf(_itemId) > 0);
require(itemRegistry.charityCutOf(_itemId) > 0);
uint256 price = itemRegistry.priceOf(_itemId);
uint256 charityCut = itemRegistry.charityCutOf(_itemId);
address itemOwner = itemRegistry.ownerOf(_itemId);
listItem(_itemId, price, itemOwner, charityCut);
}
function listMultipleItems (uint256[] _itemIds, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() external {
for (uint256 i = 0; i < _itemIds.length; i++) {
listItem(_itemIds[i], _price, _owner, _charityCut);
}
}
function listItem (uint256 _itemId, uint256 _price, address _owner, uint256 _charityCut) onlyAdmins() public {
require(_price > 0);
require(_charityCut >= 10);
require(_charityCut <= 100);
require(priceOfItem[_itemId] == 0);
require(ownerOfItem[_itemId] == address(0));
require(charityCutOfItem[_itemId] == 0);
ownerOfItem[_itemId] = _owner;
priceOfItem[_itemId] = _price;
startingPriceOfItem[_itemId] = _price;
charityCutOfItem[_itemId] = _charityCut;
previousPriceOfItem[_itemId] = 0;
listedItems.push(_itemId);
}
// Buy
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
// Dev cut
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100); // 5%
} else if (_price < increaseLimit2) {
return _price.mul(4).div(100); // 4%
} else if (_price < increaseLimit3) {
return _price.mul(3).div(100); // 3%
} else if (_price < increaseLimit4) {
return _price.mul(3).div(100); // 3%
} else {
return _price.mul(2).div(100); // 2%
}
}
// Buy function
function buy (uint256 _itemId, uint256 _charityCutNew) payable public {
require(priceOf(_itemId) > 0); // price of the token has to be greater than zero
require(_charityCutNew >= 10); // minimum charity cut is 10%
require(_charityCutNew <= 100); // maximum charity cut is 100%
require(charityCutOf(_itemId) >= 10); // minimum charity cut is 10%
require(charityCutOf(_itemId) <= 100); // maximum charity cut is 100%
require(ownerOf(_itemId) != address(0)); // owner is not 0x0
require(msg.value >= priceOf(_itemId)); // msg.value has to be greater than the price of the token
require(ownerOf(_itemId) != msg.sender); // the owner cannot buy her own token
require(!isContract(msg.sender)); // message sender is not a contract
require(msg.sender != address(0)); // message sender is not 0x0
address oldOwner = ownerOf(_itemId); // old owner of the token
address newOwner = msg.sender; // new owner of the token
uint256 price = priceOf(_itemId); // price of the token
uint256 previousPrice = previousPriceOf(_itemId); // previous price of the token (oldOwner bought it for this price)
uint256 charityCut = charityCutOf(_itemId); // actual charity cut of the token (oldOwner set this value)
uint256 excess = msg.value.sub(price); // excess
charityCutOfItem[_itemId] = _charityCutNew; // update the charity cut array
previousPriceOfItem[_itemId] = priceOf(_itemId); // update the previous price array
priceOfItem[_itemId] = nextPriceOf(_itemId); // update price of item
_transfer(oldOwner, newOwner, _itemId); // transfer token from oldOwner to newOwner
emit Bought(_itemId, newOwner, price); // bought event
emit Sold(_itemId, oldOwner, price); // sold event
// Devevloper's cut which is left in contract and accesed by
// `withdrawAll` and `withdrawAmountTo` methods.
uint256 devCut = calculateDevCut(price); // calculate dev cut
// Charity contribution
uint256 charityAmount = ((price.sub(devCut)).sub(previousPrice)).mul(charityCut).div(100); // calculate the charity cut
charityAddress.transfer(charityAmount); // transfer payment to the address of the charity
oldOwner.transfer((price.sub(devCut)).sub(charityAmount)); // transfer payment to old owner minus the dev cut and the charity cut
if (excess > 0) {
newOwner.transfer(excess); // transfer the excess
}
}
function implementsERC721() public view returns (bool _implements) {
return erc721Enabled;
}
function name() public pure returns (string _name) {
return "Tokenimals";
}
function symbol() public pure returns (string _symbol) {
return "TKS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
// balance of an address
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
// owner of token
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
// tokens of an address
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
// token exists
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
// approved for
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
// approve
function approve(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) onlyERC721() public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) onlyERC721() public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
// read
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function startingPriceOf (uint256 _itemId) public view returns (uint256 _startingPrice) {
return startingPriceOfItem[_itemId];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function previousPriceOf (uint256 _itemId) public view returns (uint256 _previousPrice) {
return previousPriceOfItem[_itemId];
}
function charityCutOf (uint256 _itemId) public view returns (uint256 _charityCut) {
return charityCutOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function readCharityAddress () public view returns (address _charityAddress) {
return charityAddress;
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _startingPrice, uint256 _price, uint256 _nextPrice, uint256 _charityCut) {
return (ownerOf(_itemId), startingPriceOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId), charityCutOf(_itemId));
}
// selfdestruct
function ownerkill() public onlyOwner {
selfdestruct(owner);
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
// util
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
} | isContract | function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) } // solium-disable-line
return size > 0;
}
| // util | LineComment | v0.4.25-nightly.2018.6.8+commit.81c5a6e4 | bzzr://f2380f08bd7a1a98365a31fe9681329926f1e3c91ddc577d7485f5c5def099e7 | {
"func_code_index": [
12361,
12538
]
} | 57,527 |
|||
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | usingOraclize | contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
} | parseInt | function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
| // parseInt | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
27456,
27555
]
} | 57,528 |
|||
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | usingOraclize | contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
} | parseInt | function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
| // parseInt(parseFloat*10^_b) | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
27593,
28202
]
} | 57,529 |
|||
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | usingOraclize | contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
} | copyBytes | function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
| // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
39906,
40623
]
} | 57,530 |
|||
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | usingOraclize | contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
} | safer_ecrecover | function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
| // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
40820,
41823
]
} | 57,531 |
|||
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | usingOraclize | contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
} | ecrecovery | function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
| // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
41945,
43371
]
} | 57,532 |
|||
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | Superbowl | contract Superbowl is usingOraclize {
/* Declaration */
address owner;
address[2] public BOOKIES = [0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A, 0x393F3668a1B66EBB107FBF01F6C361D507Be8Ee7];
uint public constant NUM_TEAMS = 2;
string[NUM_TEAMS] public TEAM_NAMES = ["Philadelphia Eagles", "New England Patriots"];
enum TeamType { PAEagles, NEPatriots, None } // Philadelphia Eagles vs. New England Patriots
TeamType public winningTeam = TeamType.None;
uint public constant BOOKIE_POOL_COMMISSION = 10; // The bookies take 10%
uint public constant MINIMUM_BET = 0.01 ether; // 0.01 ETH is min bet
uint public constant BETTING_OPENS = 1517396866; // Currently before deployment
uint public constant BETTING_CLOSES = 1517786940; // Feb 4, 3:29pm PST
uint public constant PAYOUT_ATTEMPT_INTERVAL = 86400; // 24 hours
uint public constant BET_RELEASE_DATE = 1518391800; // If payouts haven't been completed by this date, bets are released back to the betters (Feb 11, 3.30pm PST)
uint public constant PAYOUT_DATE = BETTING_CLOSES + PAYOUT_ATTEMPT_INTERVAL; // Feb 5, 3:29 PST
bool public scheduledPayout;
bool public payoutCompleted;
struct Better {
uint[NUM_TEAMS] amountsBet;
}
mapping(address => Better) betterInfo;
address[] betters;
uint[NUM_TEAMS] public totalAmountsBet;
uint public numberOfBets;
uint public totalBetAmount;
/* Events */
event BetMade();
/* Modifiers */
// Modifier to only allow the execution of
// payout related functions when winning team
// is determined
modifier canPerformPayout() {
if (winningTeam != TeamType.None && !payoutCompleted && now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions when betting is closed
modifier bettingIsClosed() {
if (now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions restricted to the bookies
modifier onlyBookieLevel() {
require(
BOOKIES[0] == msg.sender || BOOKIES[1] == msg.sender
);
_;
}
/* Functions */
// Constructor
function Superbowl() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now); // Schedule payout at first manual scheduled time
}
function pingOracle(uint pingDelay) private {
// Schedule the determination of winning team
// at the delay passed. This can be triggered
// multiple times, but as soon as the payout occurs
// the function does not do anything
oraclize_query(pingDelay, "WolframAlpha", "Super Bowl LII Winner");
}
// Callback from Oraclize
function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
// Determine winning team index based
// on its name that the request returned
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
// If there's an error (failed authenticity proof, result
// didn't match any team), then we reschedule the
// query for later.
if (winningTeam == TeamType.None) {
// Except for if we are past the point of releasing bets.
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
// Returns the total amounts betted for
// the sender
function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
// Release all the bets back to the betters
// if, for any reason, payouts cannot be
// completed
function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
// Returns true if we can bet (in betting window)
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
// We (bookies) can trigger a payout
// immediately, before the scheduled payout,
// if the data source has already been updated.
// This is so people can get their $$$ ASAP.
function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
// Function for user to bet on team idx,
// where 0 = Eagles and 1 = Patriots
function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.PAEagles || TeamType(teamIdx) == TeamType.NEPatriots);
require(msg.value >= MINIMUM_BET);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
// Perform bet
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade(); // Trigger event
}
// Performs payout based on winning team
function performPayout() private canPerformPayout {
// Calculate total pool of ETH
// betted for all different teams,
// and for the winning pool.
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot
// Equal weight payout to the bookies
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
// Weighted payout to betters based on
// their contribution to the winning pool
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
} | // </ORACLIZE_API> | LineComment | Superbowl | function Superbowl() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now); // Schedule payout at first manual scheduled time
}
| // Constructor | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
2152,
2300
]
} | 57,533 |
|
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | Superbowl | contract Superbowl is usingOraclize {
/* Declaration */
address owner;
address[2] public BOOKIES = [0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A, 0x393F3668a1B66EBB107FBF01F6C361D507Be8Ee7];
uint public constant NUM_TEAMS = 2;
string[NUM_TEAMS] public TEAM_NAMES = ["Philadelphia Eagles", "New England Patriots"];
enum TeamType { PAEagles, NEPatriots, None } // Philadelphia Eagles vs. New England Patriots
TeamType public winningTeam = TeamType.None;
uint public constant BOOKIE_POOL_COMMISSION = 10; // The bookies take 10%
uint public constant MINIMUM_BET = 0.01 ether; // 0.01 ETH is min bet
uint public constant BETTING_OPENS = 1517396866; // Currently before deployment
uint public constant BETTING_CLOSES = 1517786940; // Feb 4, 3:29pm PST
uint public constant PAYOUT_ATTEMPT_INTERVAL = 86400; // 24 hours
uint public constant BET_RELEASE_DATE = 1518391800; // If payouts haven't been completed by this date, bets are released back to the betters (Feb 11, 3.30pm PST)
uint public constant PAYOUT_DATE = BETTING_CLOSES + PAYOUT_ATTEMPT_INTERVAL; // Feb 5, 3:29 PST
bool public scheduledPayout;
bool public payoutCompleted;
struct Better {
uint[NUM_TEAMS] amountsBet;
}
mapping(address => Better) betterInfo;
address[] betters;
uint[NUM_TEAMS] public totalAmountsBet;
uint public numberOfBets;
uint public totalBetAmount;
/* Events */
event BetMade();
/* Modifiers */
// Modifier to only allow the execution of
// payout related functions when winning team
// is determined
modifier canPerformPayout() {
if (winningTeam != TeamType.None && !payoutCompleted && now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions when betting is closed
modifier bettingIsClosed() {
if (now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions restricted to the bookies
modifier onlyBookieLevel() {
require(
BOOKIES[0] == msg.sender || BOOKIES[1] == msg.sender
);
_;
}
/* Functions */
// Constructor
function Superbowl() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now); // Schedule payout at first manual scheduled time
}
function pingOracle(uint pingDelay) private {
// Schedule the determination of winning team
// at the delay passed. This can be triggered
// multiple times, but as soon as the payout occurs
// the function does not do anything
oraclize_query(pingDelay, "WolframAlpha", "Super Bowl LII Winner");
}
// Callback from Oraclize
function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
// Determine winning team index based
// on its name that the request returned
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
// If there's an error (failed authenticity proof, result
// didn't match any team), then we reschedule the
// query for later.
if (winningTeam == TeamType.None) {
// Except for if we are past the point of releasing bets.
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
// Returns the total amounts betted for
// the sender
function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
// Release all the bets back to the betters
// if, for any reason, payouts cannot be
// completed
function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
// Returns true if we can bet (in betting window)
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
// We (bookies) can trigger a payout
// immediately, before the scheduled payout,
// if the data source has already been updated.
// This is so people can get their $$$ ASAP.
function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
// Function for user to bet on team idx,
// where 0 = Eagles and 1 = Patriots
function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.PAEagles || TeamType(teamIdx) == TeamType.NEPatriots);
require(msg.value >= MINIMUM_BET);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
// Perform bet
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade(); // Trigger event
}
// Performs payout based on winning team
function performPayout() private canPerformPayout {
// Calculate total pool of ETH
// betted for all different teams,
// and for the winning pool.
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot
// Equal weight payout to the bookies
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
// Weighted payout to betters based on
// their contribution to the winning pool
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
} | // </ORACLIZE_API> | LineComment | __callback | function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
// Determine winning team index based
// on its name that the request returned
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
// If there's an error (failed authenticity proof, result
// didn't match any team), then we reschedule the
// query for later.
if (winningTeam == TeamType.None) {
// Except for if we are past the point of releasing bets.
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
| // Callback from Oraclize | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
2662,
3545
]
} | 57,534 |
|
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | Superbowl | contract Superbowl is usingOraclize {
/* Declaration */
address owner;
address[2] public BOOKIES = [0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A, 0x393F3668a1B66EBB107FBF01F6C361D507Be8Ee7];
uint public constant NUM_TEAMS = 2;
string[NUM_TEAMS] public TEAM_NAMES = ["Philadelphia Eagles", "New England Patriots"];
enum TeamType { PAEagles, NEPatriots, None } // Philadelphia Eagles vs. New England Patriots
TeamType public winningTeam = TeamType.None;
uint public constant BOOKIE_POOL_COMMISSION = 10; // The bookies take 10%
uint public constant MINIMUM_BET = 0.01 ether; // 0.01 ETH is min bet
uint public constant BETTING_OPENS = 1517396866; // Currently before deployment
uint public constant BETTING_CLOSES = 1517786940; // Feb 4, 3:29pm PST
uint public constant PAYOUT_ATTEMPT_INTERVAL = 86400; // 24 hours
uint public constant BET_RELEASE_DATE = 1518391800; // If payouts haven't been completed by this date, bets are released back to the betters (Feb 11, 3.30pm PST)
uint public constant PAYOUT_DATE = BETTING_CLOSES + PAYOUT_ATTEMPT_INTERVAL; // Feb 5, 3:29 PST
bool public scheduledPayout;
bool public payoutCompleted;
struct Better {
uint[NUM_TEAMS] amountsBet;
}
mapping(address => Better) betterInfo;
address[] betters;
uint[NUM_TEAMS] public totalAmountsBet;
uint public numberOfBets;
uint public totalBetAmount;
/* Events */
event BetMade();
/* Modifiers */
// Modifier to only allow the execution of
// payout related functions when winning team
// is determined
modifier canPerformPayout() {
if (winningTeam != TeamType.None && !payoutCompleted && now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions when betting is closed
modifier bettingIsClosed() {
if (now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions restricted to the bookies
modifier onlyBookieLevel() {
require(
BOOKIES[0] == msg.sender || BOOKIES[1] == msg.sender
);
_;
}
/* Functions */
// Constructor
function Superbowl() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now); // Schedule payout at first manual scheduled time
}
function pingOracle(uint pingDelay) private {
// Schedule the determination of winning team
// at the delay passed. This can be triggered
// multiple times, but as soon as the payout occurs
// the function does not do anything
oraclize_query(pingDelay, "WolframAlpha", "Super Bowl LII Winner");
}
// Callback from Oraclize
function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
// Determine winning team index based
// on its name that the request returned
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
// If there's an error (failed authenticity proof, result
// didn't match any team), then we reschedule the
// query for later.
if (winningTeam == TeamType.None) {
// Except for if we are past the point of releasing bets.
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
// Returns the total amounts betted for
// the sender
function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
// Release all the bets back to the betters
// if, for any reason, payouts cannot be
// completed
function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
// Returns true if we can bet (in betting window)
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
// We (bookies) can trigger a payout
// immediately, before the scheduled payout,
// if the data source has already been updated.
// This is so people can get their $$$ ASAP.
function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
// Function for user to bet on team idx,
// where 0 = Eagles and 1 = Patriots
function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.PAEagles || TeamType(teamIdx) == TeamType.NEPatriots);
require(msg.value >= MINIMUM_BET);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
// Perform bet
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade(); // Trigger event
}
// Performs payout based on winning team
function performPayout() private canPerformPayout {
// Calculate total pool of ETH
// betted for all different teams,
// and for the winning pool.
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot
// Equal weight payout to the bookies
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
// Weighted payout to betters based on
// their contribution to the winning pool
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
} | // </ORACLIZE_API> | LineComment | getUserBets | function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
| // Returns the total amounts betted for
// the sender | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
3608,
3732
]
} | 57,535 |
|
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | Superbowl | contract Superbowl is usingOraclize {
/* Declaration */
address owner;
address[2] public BOOKIES = [0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A, 0x393F3668a1B66EBB107FBF01F6C361D507Be8Ee7];
uint public constant NUM_TEAMS = 2;
string[NUM_TEAMS] public TEAM_NAMES = ["Philadelphia Eagles", "New England Patriots"];
enum TeamType { PAEagles, NEPatriots, None } // Philadelphia Eagles vs. New England Patriots
TeamType public winningTeam = TeamType.None;
uint public constant BOOKIE_POOL_COMMISSION = 10; // The bookies take 10%
uint public constant MINIMUM_BET = 0.01 ether; // 0.01 ETH is min bet
uint public constant BETTING_OPENS = 1517396866; // Currently before deployment
uint public constant BETTING_CLOSES = 1517786940; // Feb 4, 3:29pm PST
uint public constant PAYOUT_ATTEMPT_INTERVAL = 86400; // 24 hours
uint public constant BET_RELEASE_DATE = 1518391800; // If payouts haven't been completed by this date, bets are released back to the betters (Feb 11, 3.30pm PST)
uint public constant PAYOUT_DATE = BETTING_CLOSES + PAYOUT_ATTEMPT_INTERVAL; // Feb 5, 3:29 PST
bool public scheduledPayout;
bool public payoutCompleted;
struct Better {
uint[NUM_TEAMS] amountsBet;
}
mapping(address => Better) betterInfo;
address[] betters;
uint[NUM_TEAMS] public totalAmountsBet;
uint public numberOfBets;
uint public totalBetAmount;
/* Events */
event BetMade();
/* Modifiers */
// Modifier to only allow the execution of
// payout related functions when winning team
// is determined
modifier canPerformPayout() {
if (winningTeam != TeamType.None && !payoutCompleted && now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions when betting is closed
modifier bettingIsClosed() {
if (now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions restricted to the bookies
modifier onlyBookieLevel() {
require(
BOOKIES[0] == msg.sender || BOOKIES[1] == msg.sender
);
_;
}
/* Functions */
// Constructor
function Superbowl() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now); // Schedule payout at first manual scheduled time
}
function pingOracle(uint pingDelay) private {
// Schedule the determination of winning team
// at the delay passed. This can be triggered
// multiple times, but as soon as the payout occurs
// the function does not do anything
oraclize_query(pingDelay, "WolframAlpha", "Super Bowl LII Winner");
}
// Callback from Oraclize
function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
// Determine winning team index based
// on its name that the request returned
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
// If there's an error (failed authenticity proof, result
// didn't match any team), then we reschedule the
// query for later.
if (winningTeam == TeamType.None) {
// Except for if we are past the point of releasing bets.
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
// Returns the total amounts betted for
// the sender
function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
// Release all the bets back to the betters
// if, for any reason, payouts cannot be
// completed
function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
// Returns true if we can bet (in betting window)
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
// We (bookies) can trigger a payout
// immediately, before the scheduled payout,
// if the data source has already been updated.
// This is so people can get their $$$ ASAP.
function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
// Function for user to bet on team idx,
// where 0 = Eagles and 1 = Patriots
function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.PAEagles || TeamType(teamIdx) == TeamType.NEPatriots);
require(msg.value >= MINIMUM_BET);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
// Perform bet
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade(); // Trigger event
}
// Performs payout based on winning team
function performPayout() private canPerformPayout {
// Calculate total pool of ETH
// betted for all different teams,
// and for the winning pool.
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot
// Equal weight payout to the bookies
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
// Weighted payout to betters based on
// their contribution to the winning pool
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
} | // </ORACLIZE_API> | LineComment | releaseBets | function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
| // Release all the bets back to the betters
// if, for any reason, payouts cannot be
// completed | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
3842,
4149
]
} | 57,536 |
|
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | Superbowl | contract Superbowl is usingOraclize {
/* Declaration */
address owner;
address[2] public BOOKIES = [0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A, 0x393F3668a1B66EBB107FBF01F6C361D507Be8Ee7];
uint public constant NUM_TEAMS = 2;
string[NUM_TEAMS] public TEAM_NAMES = ["Philadelphia Eagles", "New England Patriots"];
enum TeamType { PAEagles, NEPatriots, None } // Philadelphia Eagles vs. New England Patriots
TeamType public winningTeam = TeamType.None;
uint public constant BOOKIE_POOL_COMMISSION = 10; // The bookies take 10%
uint public constant MINIMUM_BET = 0.01 ether; // 0.01 ETH is min bet
uint public constant BETTING_OPENS = 1517396866; // Currently before deployment
uint public constant BETTING_CLOSES = 1517786940; // Feb 4, 3:29pm PST
uint public constant PAYOUT_ATTEMPT_INTERVAL = 86400; // 24 hours
uint public constant BET_RELEASE_DATE = 1518391800; // If payouts haven't been completed by this date, bets are released back to the betters (Feb 11, 3.30pm PST)
uint public constant PAYOUT_DATE = BETTING_CLOSES + PAYOUT_ATTEMPT_INTERVAL; // Feb 5, 3:29 PST
bool public scheduledPayout;
bool public payoutCompleted;
struct Better {
uint[NUM_TEAMS] amountsBet;
}
mapping(address => Better) betterInfo;
address[] betters;
uint[NUM_TEAMS] public totalAmountsBet;
uint public numberOfBets;
uint public totalBetAmount;
/* Events */
event BetMade();
/* Modifiers */
// Modifier to only allow the execution of
// payout related functions when winning team
// is determined
modifier canPerformPayout() {
if (winningTeam != TeamType.None && !payoutCompleted && now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions when betting is closed
modifier bettingIsClosed() {
if (now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions restricted to the bookies
modifier onlyBookieLevel() {
require(
BOOKIES[0] == msg.sender || BOOKIES[1] == msg.sender
);
_;
}
/* Functions */
// Constructor
function Superbowl() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now); // Schedule payout at first manual scheduled time
}
function pingOracle(uint pingDelay) private {
// Schedule the determination of winning team
// at the delay passed. This can be triggered
// multiple times, but as soon as the payout occurs
// the function does not do anything
oraclize_query(pingDelay, "WolframAlpha", "Super Bowl LII Winner");
}
// Callback from Oraclize
function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
// Determine winning team index based
// on its name that the request returned
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
// If there's an error (failed authenticity proof, result
// didn't match any team), then we reschedule the
// query for later.
if (winningTeam == TeamType.None) {
// Except for if we are past the point of releasing bets.
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
// Returns the total amounts betted for
// the sender
function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
// Release all the bets back to the betters
// if, for any reason, payouts cannot be
// completed
function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
// Returns true if we can bet (in betting window)
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
// We (bookies) can trigger a payout
// immediately, before the scheduled payout,
// if the data source has already been updated.
// This is so people can get their $$$ ASAP.
function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
// Function for user to bet on team idx,
// where 0 = Eagles and 1 = Patriots
function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.PAEagles || TeamType(teamIdx) == TeamType.NEPatriots);
require(msg.value >= MINIMUM_BET);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
// Perform bet
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade(); // Trigger event
}
// Performs payout based on winning team
function performPayout() private canPerformPayout {
// Calculate total pool of ETH
// betted for all different teams,
// and for the winning pool.
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot
// Equal weight payout to the bookies
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
// Weighted payout to betters based on
// their contribution to the winning pool
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
} | // </ORACLIZE_API> | LineComment | canBet | function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
| // Returns true if we can bet (in betting window) | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
4207,
4324
]
} | 57,537 |
|
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | Superbowl | contract Superbowl is usingOraclize {
/* Declaration */
address owner;
address[2] public BOOKIES = [0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A, 0x393F3668a1B66EBB107FBF01F6C361D507Be8Ee7];
uint public constant NUM_TEAMS = 2;
string[NUM_TEAMS] public TEAM_NAMES = ["Philadelphia Eagles", "New England Patriots"];
enum TeamType { PAEagles, NEPatriots, None } // Philadelphia Eagles vs. New England Patriots
TeamType public winningTeam = TeamType.None;
uint public constant BOOKIE_POOL_COMMISSION = 10; // The bookies take 10%
uint public constant MINIMUM_BET = 0.01 ether; // 0.01 ETH is min bet
uint public constant BETTING_OPENS = 1517396866; // Currently before deployment
uint public constant BETTING_CLOSES = 1517786940; // Feb 4, 3:29pm PST
uint public constant PAYOUT_ATTEMPT_INTERVAL = 86400; // 24 hours
uint public constant BET_RELEASE_DATE = 1518391800; // If payouts haven't been completed by this date, bets are released back to the betters (Feb 11, 3.30pm PST)
uint public constant PAYOUT_DATE = BETTING_CLOSES + PAYOUT_ATTEMPT_INTERVAL; // Feb 5, 3:29 PST
bool public scheduledPayout;
bool public payoutCompleted;
struct Better {
uint[NUM_TEAMS] amountsBet;
}
mapping(address => Better) betterInfo;
address[] betters;
uint[NUM_TEAMS] public totalAmountsBet;
uint public numberOfBets;
uint public totalBetAmount;
/* Events */
event BetMade();
/* Modifiers */
// Modifier to only allow the execution of
// payout related functions when winning team
// is determined
modifier canPerformPayout() {
if (winningTeam != TeamType.None && !payoutCompleted && now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions when betting is closed
modifier bettingIsClosed() {
if (now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions restricted to the bookies
modifier onlyBookieLevel() {
require(
BOOKIES[0] == msg.sender || BOOKIES[1] == msg.sender
);
_;
}
/* Functions */
// Constructor
function Superbowl() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now); // Schedule payout at first manual scheduled time
}
function pingOracle(uint pingDelay) private {
// Schedule the determination of winning team
// at the delay passed. This can be triggered
// multiple times, but as soon as the payout occurs
// the function does not do anything
oraclize_query(pingDelay, "WolframAlpha", "Super Bowl LII Winner");
}
// Callback from Oraclize
function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
// Determine winning team index based
// on its name that the request returned
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
// If there's an error (failed authenticity proof, result
// didn't match any team), then we reschedule the
// query for later.
if (winningTeam == TeamType.None) {
// Except for if we are past the point of releasing bets.
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
// Returns the total amounts betted for
// the sender
function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
// Release all the bets back to the betters
// if, for any reason, payouts cannot be
// completed
function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
// Returns true if we can bet (in betting window)
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
// We (bookies) can trigger a payout
// immediately, before the scheduled payout,
// if the data source has already been updated.
// This is so people can get their $$$ ASAP.
function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
// Function for user to bet on team idx,
// where 0 = Eagles and 1 = Patriots
function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.PAEagles || TeamType(teamIdx) == TeamType.NEPatriots);
require(msg.value >= MINIMUM_BET);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
// Perform bet
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade(); // Trigger event
}
// Performs payout based on winning team
function performPayout() private canPerformPayout {
// Calculate total pool of ETH
// betted for all different teams,
// and for the winning pool.
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot
// Equal weight payout to the bookies
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
// Weighted payout to betters based on
// their contribution to the winning pool
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
} | // </ORACLIZE_API> | LineComment | triggerPayout | function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
| // We (bookies) can trigger a payout
// immediately, before the scheduled payout,
// if the data source has already been updated.
// This is so people can get their $$$ ASAP. | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
4516,
4593
]
} | 57,538 |
|
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | Superbowl | contract Superbowl is usingOraclize {
/* Declaration */
address owner;
address[2] public BOOKIES = [0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A, 0x393F3668a1B66EBB107FBF01F6C361D507Be8Ee7];
uint public constant NUM_TEAMS = 2;
string[NUM_TEAMS] public TEAM_NAMES = ["Philadelphia Eagles", "New England Patriots"];
enum TeamType { PAEagles, NEPatriots, None } // Philadelphia Eagles vs. New England Patriots
TeamType public winningTeam = TeamType.None;
uint public constant BOOKIE_POOL_COMMISSION = 10; // The bookies take 10%
uint public constant MINIMUM_BET = 0.01 ether; // 0.01 ETH is min bet
uint public constant BETTING_OPENS = 1517396866; // Currently before deployment
uint public constant BETTING_CLOSES = 1517786940; // Feb 4, 3:29pm PST
uint public constant PAYOUT_ATTEMPT_INTERVAL = 86400; // 24 hours
uint public constant BET_RELEASE_DATE = 1518391800; // If payouts haven't been completed by this date, bets are released back to the betters (Feb 11, 3.30pm PST)
uint public constant PAYOUT_DATE = BETTING_CLOSES + PAYOUT_ATTEMPT_INTERVAL; // Feb 5, 3:29 PST
bool public scheduledPayout;
bool public payoutCompleted;
struct Better {
uint[NUM_TEAMS] amountsBet;
}
mapping(address => Better) betterInfo;
address[] betters;
uint[NUM_TEAMS] public totalAmountsBet;
uint public numberOfBets;
uint public totalBetAmount;
/* Events */
event BetMade();
/* Modifiers */
// Modifier to only allow the execution of
// payout related functions when winning team
// is determined
modifier canPerformPayout() {
if (winningTeam != TeamType.None && !payoutCompleted && now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions when betting is closed
modifier bettingIsClosed() {
if (now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions restricted to the bookies
modifier onlyBookieLevel() {
require(
BOOKIES[0] == msg.sender || BOOKIES[1] == msg.sender
);
_;
}
/* Functions */
// Constructor
function Superbowl() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now); // Schedule payout at first manual scheduled time
}
function pingOracle(uint pingDelay) private {
// Schedule the determination of winning team
// at the delay passed. This can be triggered
// multiple times, but as soon as the payout occurs
// the function does not do anything
oraclize_query(pingDelay, "WolframAlpha", "Super Bowl LII Winner");
}
// Callback from Oraclize
function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
// Determine winning team index based
// on its name that the request returned
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
// If there's an error (failed authenticity proof, result
// didn't match any team), then we reschedule the
// query for later.
if (winningTeam == TeamType.None) {
// Except for if we are past the point of releasing bets.
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
// Returns the total amounts betted for
// the sender
function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
// Release all the bets back to the betters
// if, for any reason, payouts cannot be
// completed
function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
// Returns true if we can bet (in betting window)
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
// We (bookies) can trigger a payout
// immediately, before the scheduled payout,
// if the data source has already been updated.
// This is so people can get their $$$ ASAP.
function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
// Function for user to bet on team idx,
// where 0 = Eagles and 1 = Patriots
function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.PAEagles || TeamType(teamIdx) == TeamType.NEPatriots);
require(msg.value >= MINIMUM_BET);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
// Perform bet
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade(); // Trigger event
}
// Performs payout based on winning team
function performPayout() private canPerformPayout {
// Calculate total pool of ETH
// betted for all different teams,
// and for the winning pool.
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot
// Equal weight payout to the bookies
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
// Weighted payout to betters based on
// their contribution to the winning pool
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
} | // </ORACLIZE_API> | LineComment | bet | function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.PAEagles || TeamType(teamIdx) == TeamType.NEPatriots);
require(msg.value >= MINIMUM_BET);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
// Perform bet
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade(); // Trigger event
}
| // Function for user to bet on team idx,
// where 0 = Eagles and 1 = Patriots | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
4680,
5320
]
} | 57,539 |
|
Superbowl | Superbowl.sol | 0xca896d11e43c4927b2041a97eba1505e1ff26f8c | Solidity | Superbowl | contract Superbowl is usingOraclize {
/* Declaration */
address owner;
address[2] public BOOKIES = [0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A, 0x393F3668a1B66EBB107FBF01F6C361D507Be8Ee7];
uint public constant NUM_TEAMS = 2;
string[NUM_TEAMS] public TEAM_NAMES = ["Philadelphia Eagles", "New England Patriots"];
enum TeamType { PAEagles, NEPatriots, None } // Philadelphia Eagles vs. New England Patriots
TeamType public winningTeam = TeamType.None;
uint public constant BOOKIE_POOL_COMMISSION = 10; // The bookies take 10%
uint public constant MINIMUM_BET = 0.01 ether; // 0.01 ETH is min bet
uint public constant BETTING_OPENS = 1517396866; // Currently before deployment
uint public constant BETTING_CLOSES = 1517786940; // Feb 4, 3:29pm PST
uint public constant PAYOUT_ATTEMPT_INTERVAL = 86400; // 24 hours
uint public constant BET_RELEASE_DATE = 1518391800; // If payouts haven't been completed by this date, bets are released back to the betters (Feb 11, 3.30pm PST)
uint public constant PAYOUT_DATE = BETTING_CLOSES + PAYOUT_ATTEMPT_INTERVAL; // Feb 5, 3:29 PST
bool public scheduledPayout;
bool public payoutCompleted;
struct Better {
uint[NUM_TEAMS] amountsBet;
}
mapping(address => Better) betterInfo;
address[] betters;
uint[NUM_TEAMS] public totalAmountsBet;
uint public numberOfBets;
uint public totalBetAmount;
/* Events */
event BetMade();
/* Modifiers */
// Modifier to only allow the execution of
// payout related functions when winning team
// is determined
modifier canPerformPayout() {
if (winningTeam != TeamType.None && !payoutCompleted && now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions when betting is closed
modifier bettingIsClosed() {
if (now > BETTING_CLOSES) _;
}
// Modifier to only allow the execution of
// certain functions restricted to the bookies
modifier onlyBookieLevel() {
require(
BOOKIES[0] == msg.sender || BOOKIES[1] == msg.sender
);
_;
}
/* Functions */
// Constructor
function Superbowl() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now); // Schedule payout at first manual scheduled time
}
function pingOracle(uint pingDelay) private {
// Schedule the determination of winning team
// at the delay passed. This can be triggered
// multiple times, but as soon as the payout occurs
// the function does not do anything
oraclize_query(pingDelay, "WolframAlpha", "Super Bowl LII Winner");
}
// Callback from Oraclize
function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
// Determine winning team index based
// on its name that the request returned
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
// If there's an error (failed authenticity proof, result
// didn't match any team), then we reschedule the
// query for later.
if (winningTeam == TeamType.None) {
// Except for if we are past the point of releasing bets.
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
// Returns the total amounts betted for
// the sender
function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
// Release all the bets back to the betters
// if, for any reason, payouts cannot be
// completed
function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
// Returns true if we can bet (in betting window)
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
// We (bookies) can trigger a payout
// immediately, before the scheduled payout,
// if the data source has already been updated.
// This is so people can get their $$$ ASAP.
function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
// Function for user to bet on team idx,
// where 0 = Eagles and 1 = Patriots
function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.PAEagles || TeamType(teamIdx) == TeamType.NEPatriots);
require(msg.value >= MINIMUM_BET);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
// Perform bet
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade(); // Trigger event
}
// Performs payout based on winning team
function performPayout() private canPerformPayout {
// Calculate total pool of ETH
// betted for all different teams,
// and for the winning pool.
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot
// Equal weight payout to the bookies
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
// Weighted payout to betters based on
// their contribution to the winning pool
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
} | // </ORACLIZE_API> | LineComment | performPayout | function performPayout() private canPerformPayout {
// Calculate total pool of ETH
// betted for all different teams,
// and for the winning pool.
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION; // Payout to the bookies; commission of losing pot
// Equal weight payout to the bookies
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
// Weighted payout to betters based on
// their contribution to the winning pool
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
| // Performs payout based on winning team | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://3b1e0a2f120128eebec8275e285a8645aa8ce6d66dfbaaaf6dcab6e13b8a98df | {
"func_code_index": [
5367,
6333
]
} | 57,540 |
|
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | transfer | function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
268,
507
]
} | 57,541 |
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
714,
823
]
} | 57,542 |
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev 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) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.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.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
392,
895
]
} | 57,543 |
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | approve | function approve(address _spender, uint256 _value) returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
1131,
1314
]
} | 57,544 |
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
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.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
1638,
1776
]
} | 57,545 |
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | increaseApproval | function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /*
* 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
*/ | Comment | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
2025,
2297
]
} | 57,546 |
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | ERC677Token | contract ERC677Token is ERC677 {
/**
* @dev transfer token to a contract address with additional data if the recipient is a contact.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
*/
function transferAndCall(address _to, uint _value, bytes _data)
public
returns (bool success)
{
super.transfer(_to, _value);
Transfer(msg.sender, _to, _value, _data);
if (isContract(_to)) {
contractFallback(_to, _value, _data);
}
return true;
}
// PRIVATE
function contractFallback(address _to, uint _value, bytes _data)
private
{
ERC677Receiver receiver = ERC677Receiver(_to);
receiver.onTokenTransfer(msg.sender, _value, _data);
}
function isContract(address _addr)
private
returns (bool hasCode)
{
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
} | transferAndCall | function transferAndCall(address _to, uint _value, bytes _data)
public
returns (bool success)
{
super.transfer(_to, _value);
Transfer(msg.sender, _to, _value, _data);
if (isContract(_to)) {
contractFallback(_to, _value, _data);
}
return true;
}
| /**
* @dev transfer token to a contract address with additional data if the recipient is a contact.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
314,
609
]
} | 57,547 |
||
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | ERC677Token | contract ERC677Token is ERC677 {
/**
* @dev transfer token to a contract address with additional data if the recipient is a contact.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
*/
function transferAndCall(address _to, uint _value, bytes _data)
public
returns (bool success)
{
super.transfer(_to, _value);
Transfer(msg.sender, _to, _value, _data);
if (isContract(_to)) {
contractFallback(_to, _value, _data);
}
return true;
}
// PRIVATE
function contractFallback(address _to, uint _value, bytes _data)
private
{
ERC677Receiver receiver = ERC677Receiver(_to);
receiver.onTokenTransfer(msg.sender, _value, _data);
}
function isContract(address _addr)
private
returns (bool hasCode)
{
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
} | contractFallback | function contractFallback(address _to, uint _value, bytes _data)
private
{
ERC677Receiver receiver = ERC677Receiver(_to);
receiver.onTokenTransfer(msg.sender, _value, _data);
}
| // PRIVATE | LineComment | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
630,
830
]
} | 57,548 |
||
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | UKRToken | contract UKRToken is StandardToken, ERC677Token {
uint public constant totalSupply = 1500000000000000000000000000;
string public constant name = 'UKRCHAIN';
uint8 public constant decimals = 18;
string public constant symbol = 'UKR';
function UKRToken()
public
{
balances[msg.sender] = totalSupply;
}
/**
* @dev transfer token to a specified address with additional data if the recipient is a contract.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
*/
function transferAndCall(address _to, uint _value, bytes _data)
public
validRecipient(_to)
returns (bool success)
{
return super.transferAndCall(_to, _value, _data);
}
/**
* @dev transfer token to a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value)
public
validRecipient(_to)
returns (bool success)
{
return super.transfer(_to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value)
public
validRecipient(_spender)
returns (bool)
{
return super.approve(_spender, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validRecipient(_to)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
// MODIFIERS
modifier validRecipient(address _recipient) {
require(_recipient != address(0) && _recipient != address(this));
_;
}
} | transferAndCall | function transferAndCall(address _to, uint _value, bytes _data)
public
validRecipient(_to)
returns (bool success)
{
return super.transferAndCall(_to, _value, _data);
}
| /**
* @dev transfer token to a specified address with additional data if the recipient is a contract.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
618,
814
]
} | 57,549 |
||
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | UKRToken | contract UKRToken is StandardToken, ERC677Token {
uint public constant totalSupply = 1500000000000000000000000000;
string public constant name = 'UKRCHAIN';
uint8 public constant decimals = 18;
string public constant symbol = 'UKR';
function UKRToken()
public
{
balances[msg.sender] = totalSupply;
}
/**
* @dev transfer token to a specified address with additional data if the recipient is a contract.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
*/
function transferAndCall(address _to, uint _value, bytes _data)
public
validRecipient(_to)
returns (bool success)
{
return super.transferAndCall(_to, _value, _data);
}
/**
* @dev transfer token to a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value)
public
validRecipient(_to)
returns (bool success)
{
return super.transfer(_to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value)
public
validRecipient(_spender)
returns (bool)
{
return super.approve(_spender, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validRecipient(_to)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
// MODIFIERS
modifier validRecipient(address _recipient) {
require(_recipient != address(0) && _recipient != address(this));
_;
}
} | transfer | function transfer(address _to, uint _value)
public
validRecipient(_to)
returns (bool success)
{
return super.transfer(_to, _value);
}
| /**
* @dev transfer token to a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
972,
1134
]
} | 57,550 |
||
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | UKRToken | contract UKRToken is StandardToken, ERC677Token {
uint public constant totalSupply = 1500000000000000000000000000;
string public constant name = 'UKRCHAIN';
uint8 public constant decimals = 18;
string public constant symbol = 'UKR';
function UKRToken()
public
{
balances[msg.sender] = totalSupply;
}
/**
* @dev transfer token to a specified address with additional data if the recipient is a contract.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
*/
function transferAndCall(address _to, uint _value, bytes _data)
public
validRecipient(_to)
returns (bool success)
{
return super.transferAndCall(_to, _value, _data);
}
/**
* @dev transfer token to a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value)
public
validRecipient(_to)
returns (bool success)
{
return super.transfer(_to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value)
public
validRecipient(_spender)
returns (bool)
{
return super.approve(_spender, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validRecipient(_to)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
// MODIFIERS
modifier validRecipient(address _recipient) {
require(_recipient != address(0) && _recipient != address(this));
_;
}
} | approve | function approve(address _spender, uint256 _value)
public
validRecipient(_spender)
returns (bool)
{
return super.approve(_spender, _value);
}
| /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
1370,
1541
]
} | 57,551 |
||
UKRToken | UKRToken.sol | 0xc875230d5342916a02ccdf6800d3805799b41fa3 | Solidity | UKRToken | contract UKRToken is StandardToken, ERC677Token {
uint public constant totalSupply = 1500000000000000000000000000;
string public constant name = 'UKRCHAIN';
uint8 public constant decimals = 18;
string public constant symbol = 'UKR';
function UKRToken()
public
{
balances[msg.sender] = totalSupply;
}
/**
* @dev transfer token to a specified address with additional data if the recipient is a contract.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
*/
function transferAndCall(address _to, uint _value, bytes _data)
public
validRecipient(_to)
returns (bool success)
{
return super.transferAndCall(_to, _value, _data);
}
/**
* @dev transfer token to a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value)
public
validRecipient(_to)
returns (bool success)
{
return super.transfer(_to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value)
public
validRecipient(_spender)
returns (bool)
{
return super.approve(_spender, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value)
public
validRecipient(_to)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
// MODIFIERS
modifier validRecipient(address _recipient) {
require(_recipient != address(0) && _recipient != address(this));
_;
}
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value)
public
validRecipient(_to)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
| /**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | NatSpecMultiLine | v0.4.19+commit.c4cbbb05 | MIT | bzzr://b6d130161ae3a6518bf24bbd0b07136cebf13b4ad30d01b20eef9ca75fff307b | {
"func_code_index": [
1821,
2008
]
} | 57,552 |
||
BatchExchange | contracts/EpochTokenLocker.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | EpochTokenLocker | contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
} | /** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | deposit | function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
| /** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
1439,
2019
]
} | 57,553 |
BatchExchange | contracts/EpochTokenLocker.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | EpochTokenLocker | contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
} | /** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | requestWithdraw | function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
| /** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
2294,
2438
]
} | 57,554 |
BatchExchange | contracts/EpochTokenLocker.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | EpochTokenLocker | contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
} | /** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | requestFutureWithdraw | function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
| /** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
2781,
3368
]
} | 57,555 |
BatchExchange | contracts/EpochTokenLocker.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | EpochTokenLocker | contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
} | /** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | withdraw | function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
| /** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
3824,
4754
]
} | 57,556 |
BatchExchange | contracts/EpochTokenLocker.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | EpochTokenLocker | contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
} | /** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | getPendingDeposit | function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
| /** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
5032,
5294
]
} | 57,557 |
BatchExchange | contracts/EpochTokenLocker.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | EpochTokenLocker | contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
} | /** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | getPendingWithdraw | function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
| /** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
5531,
5798
]
} | 57,558 |
BatchExchange | contracts/EpochTokenLocker.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | EpochTokenLocker | contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
} | /** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | getCurrentBatchId | function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
| /** @dev getter function to determine current auction id.
* return current batchId
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
5906,
6019
]
} | 57,559 |
BatchExchange | contracts/EpochTokenLocker.sol | 0x46f3f2f9662f66a6ddd6a8d1ddec3cd9ae5e87b5 | Solidity | EpochTokenLocker | contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
} | /** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/ | NatSpecMultiLine | getSecondsRemainingInBatch | function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
| /** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/ | NatSpecMultiLine | v0.5.6+commit.b259423e | GNU GPLv3 | bzzr://d75d8f06b335b5c4398c51039c6bbb9a0b7d2e34f3a8a69428935ad3326899cb | {
"func_code_index": [
6148,
6278
]
} | 57,560 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.