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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Bleeps | src/base/ERC721BaseWithERC4494Permit.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | ERC721BaseWithERC4494Permit | abstract contract ERC721BaseWithERC4494Permit is ERC721Base {
using Address for address;
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_FOR_ALL_TYPEHASH =
keccak256("PermitForAll(address spender,uint256 nonce,uint256 deadline)");
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
uint256 private immutable _deploymentChainId;
bytes32 private immutable _deploymentDomainSeparator;
mapping(address => uint256) internal _userNonces;
constructor() {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
_deploymentChainId = chainId;
_deploymentDomainSeparator = _calculateDomainSeparator(chainId);
}
/// @dev Return the DOMAIN_SEPARATOR.
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _DOMAIN_SEPARATOR();
}
function nonces(address account) external view virtual returns (uint256 nonce) {
return accountNonces(account);
}
function nonces(uint256 id) external view virtual returns (uint256 nonce) {
return tokenNonces(id);
}
function tokenNonces(uint256 id) public view returns (uint256 nonce) {
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
return blockNumber;
}
function accountNonces(address owner) public view returns (uint256 nonce) {
return _userNonces[owner];
}
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(tokenId);
require(owner != address(0), "NONEXISTENT_TOKEN");
// We use blockNumber as nonce as we already store it per tokens. It can thus act as an increasing transfer counter.
// while technically multiple transfer could happen in the same block, the signed message would be using a previous block.
// And the transfer would use then a more recent blockNumber, invalidating that message when transfer is executed.
_requireValidPermit(owner, spender, tokenId, deadline, blockNumber, sig);
_approveFor(owner, blockNumber, spender, tokenId);
}
function permitForAll(
address signer,
address spender,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
_requireValidPermitForAll(signer, spender, deadline, _userNonces[signer]++, sig);
_setApprovalForAll(signer, spender, true);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
return
super.supportsInterface(id) ||
id == type(IERC4494).interfaceId ||
id == type(IERC4494Alternative).interfaceId;
}
// -------------------------------------------------------- INTERNAL --------------------------------------------------------------------
function _requireValidPermit(
address signer,
address spender,
uint256 id,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, spender, id, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
function _requireValidPermitForAll(
address signer,
address spender,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_FOR_ALL_TYPEHASH, spender, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
/// @dev Return the DOMAIN_SEPARATOR.
function _DOMAIN_SEPARATOR() internal view returns (bytes32) {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
// in case a fork happen, to support the chain that had to change its chainId,, we compute the domain operator
return chainId == _deploymentChainId ? _deploymentDomainSeparator : _calculateDomainSeparator(chainId);
}
/// @dev Calculate the DOMAIN_SEPARATOR.
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), chainId, address(this)));
}
} | supportsInterface | function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
return
super.supportsInterface(id) ||
id == type(IERC4494).interfaceId ||
id == type(IERC4494Alternative).interfaceId;
}
| /// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3122,
3378
]
} | 2,300 |
|||
Bleeps | src/base/ERC721BaseWithERC4494Permit.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | ERC721BaseWithERC4494Permit | abstract contract ERC721BaseWithERC4494Permit is ERC721Base {
using Address for address;
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_FOR_ALL_TYPEHASH =
keccak256("PermitForAll(address spender,uint256 nonce,uint256 deadline)");
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
uint256 private immutable _deploymentChainId;
bytes32 private immutable _deploymentDomainSeparator;
mapping(address => uint256) internal _userNonces;
constructor() {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
_deploymentChainId = chainId;
_deploymentDomainSeparator = _calculateDomainSeparator(chainId);
}
/// @dev Return the DOMAIN_SEPARATOR.
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _DOMAIN_SEPARATOR();
}
function nonces(address account) external view virtual returns (uint256 nonce) {
return accountNonces(account);
}
function nonces(uint256 id) external view virtual returns (uint256 nonce) {
return tokenNonces(id);
}
function tokenNonces(uint256 id) public view returns (uint256 nonce) {
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
return blockNumber;
}
function accountNonces(address owner) public view returns (uint256 nonce) {
return _userNonces[owner];
}
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(tokenId);
require(owner != address(0), "NONEXISTENT_TOKEN");
// We use blockNumber as nonce as we already store it per tokens. It can thus act as an increasing transfer counter.
// while technically multiple transfer could happen in the same block, the signed message would be using a previous block.
// And the transfer would use then a more recent blockNumber, invalidating that message when transfer is executed.
_requireValidPermit(owner, spender, tokenId, deadline, blockNumber, sig);
_approveFor(owner, blockNumber, spender, tokenId);
}
function permitForAll(
address signer,
address spender,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
_requireValidPermitForAll(signer, spender, deadline, _userNonces[signer]++, sig);
_setApprovalForAll(signer, spender, true);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
return
super.supportsInterface(id) ||
id == type(IERC4494).interfaceId ||
id == type(IERC4494Alternative).interfaceId;
}
// -------------------------------------------------------- INTERNAL --------------------------------------------------------------------
function _requireValidPermit(
address signer,
address spender,
uint256 id,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, spender, id, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
function _requireValidPermitForAll(
address signer,
address spender,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_FOR_ALL_TYPEHASH, spender, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
/// @dev Return the DOMAIN_SEPARATOR.
function _DOMAIN_SEPARATOR() internal view returns (bytes32) {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
// in case a fork happen, to support the chain that had to change its chainId,, we compute the domain operator
return chainId == _deploymentChainId ? _deploymentDomainSeparator : _calculateDomainSeparator(chainId);
}
/// @dev Calculate the DOMAIN_SEPARATOR.
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), chainId, address(this)));
}
} | _requireValidPermit | function _requireValidPermit(
address signer,
address spender,
uint256 id,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, spender, id, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
| // -------------------------------------------------------- INTERNAL -------------------------------------------------------------------- | LineComment | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3523,
4065
]
} | 2,301 |
|||
Bleeps | src/base/ERC721BaseWithERC4494Permit.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | ERC721BaseWithERC4494Permit | abstract contract ERC721BaseWithERC4494Permit is ERC721Base {
using Address for address;
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_FOR_ALL_TYPEHASH =
keccak256("PermitForAll(address spender,uint256 nonce,uint256 deadline)");
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
uint256 private immutable _deploymentChainId;
bytes32 private immutable _deploymentDomainSeparator;
mapping(address => uint256) internal _userNonces;
constructor() {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
_deploymentChainId = chainId;
_deploymentDomainSeparator = _calculateDomainSeparator(chainId);
}
/// @dev Return the DOMAIN_SEPARATOR.
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _DOMAIN_SEPARATOR();
}
function nonces(address account) external view virtual returns (uint256 nonce) {
return accountNonces(account);
}
function nonces(uint256 id) external view virtual returns (uint256 nonce) {
return tokenNonces(id);
}
function tokenNonces(uint256 id) public view returns (uint256 nonce) {
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
return blockNumber;
}
function accountNonces(address owner) public view returns (uint256 nonce) {
return _userNonces[owner];
}
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(tokenId);
require(owner != address(0), "NONEXISTENT_TOKEN");
// We use blockNumber as nonce as we already store it per tokens. It can thus act as an increasing transfer counter.
// while technically multiple transfer could happen in the same block, the signed message would be using a previous block.
// And the transfer would use then a more recent blockNumber, invalidating that message when transfer is executed.
_requireValidPermit(owner, spender, tokenId, deadline, blockNumber, sig);
_approveFor(owner, blockNumber, spender, tokenId);
}
function permitForAll(
address signer,
address spender,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
_requireValidPermitForAll(signer, spender, deadline, _userNonces[signer]++, sig);
_setApprovalForAll(signer, spender, true);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
return
super.supportsInterface(id) ||
id == type(IERC4494).interfaceId ||
id == type(IERC4494Alternative).interfaceId;
}
// -------------------------------------------------------- INTERNAL --------------------------------------------------------------------
function _requireValidPermit(
address signer,
address spender,
uint256 id,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, spender, id, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
function _requireValidPermitForAll(
address signer,
address spender,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_FOR_ALL_TYPEHASH, spender, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
/// @dev Return the DOMAIN_SEPARATOR.
function _DOMAIN_SEPARATOR() internal view returns (bytes32) {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
// in case a fork happen, to support the chain that had to change its chainId,, we compute the domain operator
return chainId == _deploymentChainId ? _deploymentDomainSeparator : _calculateDomainSeparator(chainId);
}
/// @dev Calculate the DOMAIN_SEPARATOR.
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), chainId, address(this)));
}
} | _DOMAIN_SEPARATOR | function _DOMAIN_SEPARATOR() internal view returns (bytes32) {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
// in case a fork happen, to support the chain that had to change its chainId,, we compute the domain operator
return chainId == _deploymentChainId ? _deploymentDomainSeparator : _calculateDomainSeparator(chainId);
}
| /// @dev Return the DOMAIN_SEPARATOR. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
4643,
5089
]
} | 2,302 |
|||
Bleeps | src/base/ERC721BaseWithERC4494Permit.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | ERC721BaseWithERC4494Permit | abstract contract ERC721BaseWithERC4494Permit is ERC721Base {
using Address for address;
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_FOR_ALL_TYPEHASH =
keccak256("PermitForAll(address spender,uint256 nonce,uint256 deadline)");
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
uint256 private immutable _deploymentChainId;
bytes32 private immutable _deploymentDomainSeparator;
mapping(address => uint256) internal _userNonces;
constructor() {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
_deploymentChainId = chainId;
_deploymentDomainSeparator = _calculateDomainSeparator(chainId);
}
/// @dev Return the DOMAIN_SEPARATOR.
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _DOMAIN_SEPARATOR();
}
function nonces(address account) external view virtual returns (uint256 nonce) {
return accountNonces(account);
}
function nonces(uint256 id) external view virtual returns (uint256 nonce) {
return tokenNonces(id);
}
function tokenNonces(uint256 id) public view returns (uint256 nonce) {
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(id);
require(owner != address(0), "NONEXISTENT_TOKEN");
return blockNumber;
}
function accountNonces(address owner) public view returns (uint256 nonce) {
return _userNonces[owner];
}
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
(address owner, uint256 blockNumber) = _ownerAndBlockNumberOf(tokenId);
require(owner != address(0), "NONEXISTENT_TOKEN");
// We use blockNumber as nonce as we already store it per tokens. It can thus act as an increasing transfer counter.
// while technically multiple transfer could happen in the same block, the signed message would be using a previous block.
// And the transfer would use then a more recent blockNumber, invalidating that message when transfer is executed.
_requireValidPermit(owner, spender, tokenId, deadline, blockNumber, sig);
_approveFor(owner, blockNumber, spender, tokenId);
}
function permitForAll(
address signer,
address spender,
uint256 deadline,
bytes memory sig
) external {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
_requireValidPermitForAll(signer, spender, deadline, _userNonces[signer]++, sig);
_setApprovalForAll(signer, spender, true);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override returns (bool) {
return
super.supportsInterface(id) ||
id == type(IERC4494).interfaceId ||
id == type(IERC4494Alternative).interfaceId;
}
// -------------------------------------------------------- INTERNAL --------------------------------------------------------------------
function _requireValidPermit(
address signer,
address spender,
uint256 id,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, spender, id, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
function _requireValidPermitForAll(
address signer,
address spender,
uint256 deadline,
uint256 nonce,
bytes memory sig
) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
_DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_FOR_ALL_TYPEHASH, spender, nonce, deadline))
)
);
require(SignatureChecker.isValidSignatureNow(signer, digest, sig), "INVALID_SIGNATURE");
}
/// @dev Return the DOMAIN_SEPARATOR.
function _DOMAIN_SEPARATOR() internal view returns (bytes32) {
uint256 chainId;
//solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
// in case a fork happen, to support the chain that had to change its chainId,, we compute the domain operator
return chainId == _deploymentChainId ? _deploymentDomainSeparator : _calculateDomainSeparator(chainId);
}
/// @dev Calculate the DOMAIN_SEPARATOR.
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), chainId, address(this)));
}
} | _calculateDomainSeparator | function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), chainId, address(this)));
}
| /// @dev Calculate the DOMAIN_SEPARATOR. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
5136,
5335
]
} | 2,303 |
|||
ApusToken | ApusToken.sol | 0xbeb100a5970f75abb77031cc1832b4c934a0c1be | Solidity | Ownable | contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
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) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | Ownable | function Ownable() {
owner = msg.sender;
}
| /**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://f1b70a6ff9d4103b0deeac5cc94a5a1992d09777605071e824251ac071f1e234 | {
"func_code_index": [
179,
240
]
} | 2,304 |
|
ApusToken | ApusToken.sol | 0xbeb100a5970f75abb77031cc1832b4c934a0c1be | Solidity | Ownable | contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
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) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.18+commit.9cf6e910 | bzzr://f1b70a6ff9d4103b0deeac5cc94a5a1992d09777605071e824251ac071f1e234 | {
"func_code_index": [
589,
726
]
} | 2,305 |
|
ApusToken | ApusToken.sol | 0xbeb100a5970f75abb77031cc1832b4c934a0c1be | Solidity | ApusToken | contract ApusToken is ERC20,StakeStandard,Ownable {
using SafeMath for uint256;
string public name = "Apus Token";
string public symbol = "APUS";
uint public decimals = 18;
uint public chainStartTime;
uint public chainStartBlockNumber;
uint public stakeStartTime;
uint public stakeMinAge = 1 days;
uint public stakeMaxAge = 90 days;
uint public maxMintProofOfStake = 5 * (10**17); //50%
uint public mintBase = 10**17; //10%
uint public totalSupply;
uint public maxTotalSupply;
uint public totalInitialSupply;
struct transferInStruct{
uint128 amount;
uint64 time;
}
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => transferInStruct[]) transferIns;
event Burn(address indexed burner, uint256 value);
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
modifier canPoSMint() {
require(totalSupply < maxTotalSupply);
_;
}
function ApusToken() {
maxTotalSupply = 500 * (10**24); // 500 Mil.
totalInitialSupply = 10**24; // 1 Mil.
chainStartTime = now;
chainStartBlockNumber = block.number;
balances[msg.sender] = totalInitialSupply;
totalSupply = totalInitialSupply;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns (bool) {
if(msg.sender == _to) return mine();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
if(transferIns[_from].length > 0) delete transferIns[_from];
uint64 _now = uint64(now);
transferIns[_from].push(transferInStruct(uint128(balances[_from]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function mine() canPoSMint returns (bool) {
if(balances[msg.sender] <= 0) return false;
if(transferIns[msg.sender].length <= 0) return false;
uint reward = getProofOfStakeReward(msg.sender);
if(reward <= 0) return false;
totalSupply = totalSupply.add(reward);
balances[msg.sender] = balances[msg.sender].add(reward);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
Mine(msg.sender, reward);
return true;
}
function getBlockNumber() returns (uint blockNumber) {
blockNumber = block.number.sub(chainStartBlockNumber);
}
function coinAge() constant returns (uint myCoinAge) {
myCoinAge = getCoinAge(msg.sender,now);
}
function annualInterest() constant returns(uint interest) {
uint _now = now;
interest = maxMintProofOfStake;
if((_now.sub(stakeStartTime)).div(1 years) == 0) {
interest = 6 * (770 * mintBase).div(100);
} else if((_now.sub(stakeStartTime)).div(1 years) == 1){
interest = 6 * (435 * mintBase).div(100);
}
}
function getProofOfStakeReward(address _address) internal returns (uint) {
require( (now >= stakeStartTime) && (stakeStartTime > 0) );
uint _now = now;
uint _coinAge = getCoinAge(_address, _now);
if(_coinAge <= 0) return 0;
uint interest = maxMintProofOfStake;
// Due to the high interest rate for the first two years, compounding should be taken into account.
// Effective annual interest rate = (1 + (nominal rate / number of compounding periods)) ^ (number of compounding periods) - 1
if((_now.sub(stakeStartTime)).div(1 years) == 0) {
// 1st year effective annual interest rate is 600% when we select the stakeMaxAge (90 days) as the compounding period.
interest = 6 * (770 * mintBase).div(100);
} else if((_now.sub(stakeStartTime)).div(1 years) == 1){
// 2nd year effective annual interest rate is 300%
interest = 6 * (435 * mintBase).div(100);
}
return (_coinAge * interest).div(365 * (10**decimals));
}
function getCoinAge(address _address, uint _now) internal returns (uint _coinAge) {
if(transferIns[_address].length <= 0) return 0;
for (uint i = 0; i < transferIns[_address].length; i++){
if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue;
uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time));
if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge;
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days));
}
}
function ownerSetStakeStartTime(uint timestamp) onlyOwner {
require((stakeStartTime <= 0) && (timestamp >= chainStartTime));
stakeStartTime = timestamp;
}
function ownerBurnToken(uint _value) onlyOwner {
require(_value > 0);
balances[msg.sender] = balances[msg.sender].sub(_value);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
totalSupply = totalSupply.sub(_value);
totalInitialSupply = totalInitialSupply.sub(_value);
maxTotalSupply = maxTotalSupply.sub(_value*10);
Burn(msg.sender, _value);
}
/* Batch token transfer. Used by contract creator to distribute initial tokens to holders */
function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) {
require( _recipients.length > 0 && _recipients.length == _values.length);
uint total = 0;
for(uint i = 0; i < _values.length; i++){
total = total.add(_values[i]);
}
require(total <= balances[msg.sender]);
uint64 _now = uint64(now);
for(uint j = 0; j < _recipients.length; j++){
balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]);
transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now));
Transfer(msg.sender, _recipients[j], _values[j]);
}
balances[msg.sender] = balances[msg.sender].sub(total);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
return true;
}
function mintToken(address target, uint256 mintedAmount) onlyOwner {
balances[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}
function Destroy() onlyOwner() {
selfdestruct(owner);
}
} | batchTransfer | function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) {
require( _recipients.length > 0 && _recipients.length == _values.length);
uint total = 0;
for(uint i = 0; i < _values.length; i++){
total = total.add(_values[i]);
}
require(total <= balances[msg.sender]);
uint64 _now = uint64(now);
for(uint j = 0; j < _recipients.length; j++){
balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]);
transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now));
Transfer(msg.sender, _recipients[j], _values[j]);
}
balances[msg.sender] = balances[msg.sender].sub(total);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
return true;
}
| /* Batch token transfer. Used by contract creator to distribute initial tokens to holders */ | Comment | v0.4.18+commit.9cf6e910 | bzzr://f1b70a6ff9d4103b0deeac5cc94a5a1992d09777605071e824251ac071f1e234 | {
"func_code_index": [
7030,
8028
]
} | 2,306 |
|||
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | owned | contract owned {
address public owner;
//*** OwnershipTransferred ***//
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function owned() public {
owner = msg.sender;
}
//*** Change Owner ***//
function changeOwner(address newOwner) onlyOwner public {
owner = newOwner;
}
//*** Transfer OwnerShip ***//
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
//*** Only Owner ***//
modifier onlyOwner {
require(msg.sender == owner);
_;
}
} | //*** Owner ***// | LineComment | changeOwner | function changeOwner(address newOwner) onlyOwner public {
owner = newOwner;
}
| //*** Change Owner ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
265,
349
]
} | 2,307 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | owned | contract owned {
address public owner;
//*** OwnershipTransferred ***//
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function owned() public {
owner = msg.sender;
}
//*** Change Owner ***//
function changeOwner(address newOwner) onlyOwner public {
owner = newOwner;
}
//*** Transfer OwnerShip ***//
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
//*** Only Owner ***//
modifier onlyOwner {
require(msg.sender == owner);
_;
}
} | //*** Owner ***// | LineComment | transferOwnership | function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
| //*** Transfer OwnerShip ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
392,
584
]
} | 2,308 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
| //*** Payable ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
2198,
3487
]
} | 2,309 |
||
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | transfer | function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
| /* Send coins */ | Comment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
3510,
3933
]
} | 2,310 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
| //*** Transfer From ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
3964,
4630
]
} | 2,311 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | transferOwner | function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
| //*** Transfer OnlyOwner ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
4667,
4952
]
} | 2,312 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | allowance | function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| //*** Allowance ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
4980,
5121
]
} | 2,313 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | approve | function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| //*** Approve ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
5147,
5337
]
} | 2,314 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | burnOwner | function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
| //*** Burn Owner***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
5365,
5529
]
} | 2,315 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | destroyOwner | function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
| //*** Destroy Owner ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
5561,
5794
]
} | 2,316 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | killBalance | function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
| //*** Kill Balance ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
5825,
6313
]
} | 2,317 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | killTokens | function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
| //*** Kill Tokens ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
6343,
6732
]
} | 2,318 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | contractBalance | function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
| //*** Contract Balance ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
6767,
6870
]
} | 2,319 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | setParamsTransfer | function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
| //*** Set ParamsTransfer ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
6907,
7001
]
} | 2,320 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | setParamsIco | function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
| //*** Set ParamsICO ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
7033,
7145
]
} | 2,321 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | setParamsPreSale | function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
| //*** Set ParamsPreSale ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
7184,
7304
]
} | 2,322 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | isIco | function isIco() constant public returns (bool ico) {
ool result=((icoStart+(35*24*60*60)) >= now);
f(enableIco){
return true;
lse{
return result;
| //*** Is ico ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
7329,
7527
]
} | 2,323 |
|
GraphenePowerToken | GraphenePowerToken.sol | 0x30795a541aea7f76ceccae7dc5146682f6b04cd7 | Solidity | GraphenePowerToken | contract GraphenePowerToken is owned{
//************** Token ************//
string public standard = 'Token 1';
string public name = 'Graphene Power';
string public symbol = 'GRP';
uint8 public decimals = 18;
uint256 public totalSupply =0;
//*** Pre-sale ***//
uint preSaleStart=1513771200;
uint preSaleEnd=1515585600;
uint256 preSaleTotalTokens=30000000;
uint256 preSaleTokenCost=6000;
address preSaleAddress;
bool public enablePreSale=false;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Advisers,Consultants ***//
uint256 advisersConsultantTokens=15000000;
address advisersConsultantsAddress;
//*** Bounty ***//
uint256 bountyTokens=15000000;
address bountyAddress;
//*** Founders ***//
uint256 founderTokens=40000000;
address founderAddress;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transfersEnabled = false;
//*** Balance ***//
mapping (address => uint256) public balanceOf;
//*** Alowed ***//
mapping (address => mapping (address => uint256)) allowed;
//*** Tranfer ***//
event Transfer(address from, address to, uint256 value);
//*** Approval ***//
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
//*** Destruction ***//
event Destruction(uint256 _amount);
//*** Burn ***//
event Burn(address indexed from, uint256 value);
//*** Issuance ***//
event Issuance(uint256 _amount);
function GraphenePowerToken() public{
preSaleAddress=0xC07850969A0EC345A84289f9C5bb5F979f27110f;
icoAddress=0x1C21Cf57BF4e2dd28883eE68C03a9725056D29F1;
advisersConsultantsAddress=0xe8B6dA1B801b7F57e3061C1c53a011b31C9315C7;
bountyAddress=0xD53E82Aea770feED8e57433D3D61674caEC1D1Be;
founderAddress=0xDA0D3Dad39165EA2d7386f18F96664Ee2e9FD8db;
totalSupply =500000000;
balanceOf[msg.sender]=totalSupply;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
uint256 weiAmount;
uint256 tokens;
wallet=owner;
if(isPreSale()){
wallet=preSaleAddress;
weiAmount=6000;
}
else if(isIco()){
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
else{
weiAmount=4000;
}
tokens=msg.value*weiAmount/1000000000000000000;
Transfer(this, msg.sender, tokens);
balanceOf[msg.sender]+=tokens;
totalSupply=(totalSupply-tokens);
wallet.transfer(msg.value);
balanceOf[this]+=msg.value;
}
/* Send coins */
function transfer(address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
require(balanceOf[_to] >= _value);
// Subtract from the sender
balanceOf[msg.sender] = (balanceOf[msg.sender] -_value);
balanceOf[_to] =(balanceOf[_to] + _value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(transfersEnabled){
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check allowed
require(_value <= allowed[_from][msg.sender]);
// Subtract from the sender
balanceOf[_from] = (balanceOf[_from] - _value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
}
else{
return false;
}
}
//*** Transfer OnlyOwner ***//
function transferOwner(address _to,uint256 _value) public onlyOwner returns(bool success){
// Subtract from the sender
totalSupply=(totalSupply-_value);
// Add the same to the recipient
balanceOf[_to] = (balanceOf[_to] + _value);
Transfer(this, _to, _value);
}
//*** Allowance ***//
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//*** Approve ***//
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
//*** Burn Owner***//
function burnOwner(uint256 _value) public onlyOwner returns (bool success) {
destroyOwner(msg.sender, _value);
Burn(msg.sender, _value);
return true;
}
//*** Destroy Owner ***//
function destroyOwner(address _from, uint256 _amount) public onlyOwner{
balanceOf[_from] =(balanceOf[_from] - _amount);
totalSupply = (totalSupply - _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
//*** Kill Balance ***//
function killBalance(uint256 _value) onlyOwner public {
if(this.balance > 0) {
if(_value==1){
preSaleAddress.transfer(this.balance);
balanceOf[this]=0;
}
else if(_value==2){
icoAddress.transfer(this.balance);
balanceOf[this]=0;
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
else{
owner.transfer(this.balance);
balanceOf[this]=0;
}
}
//*** Kill Tokens ***//
function killTokens() onlyOwner public{
Transfer(this, bountyAddress, bountyTokens);
Transfer(this, founderAddress, founderTokens);
Transfer(this, advisersConsultantsAddress, advisersConsultantTokens);
totalSupply=totalSupply-(bountyTokens+founderTokens+advisersConsultantTokens);
bountyTokens=0;
founderTokens=0;
advisersConsultantTokens=0;
}
//*** Contract Balance ***//
function contractBalance() constant public returns (uint256 balance) {
return balanceOf[this];
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transfersEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
}
//*** Set ParamsPreSale ***//
function setParamsPreSale(bool _value) public onlyOwner returns(bool result){
enablePreSale=_value;
}
//*** Is ico ***//
function isIco() constant public returns (bool ico) {
bool result=((icoStart+(35*24*60*60)) >= now);
if(enableIco){
return true;
}
else{
return result;
}
}
//*** Is PreSale ***//
function isPreSale() constant public returns (bool preSale) {
bool result=(preSaleEnd >= now);
if(enablePreSale){
return true;
}
else{
return result;
}
}
} | //*** GraphenePowerToken ***// | LineComment | isPreSale | function isPreSale() constant public returns (bool preSale) {
ol result=(preSaleEnd >= now);
(enablePreSale){
return true;
se{
return result;
| //*** Is PreSale ***// | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://75480e7748a5a3a0e4b718d8c45a2909545714329e23ada6d4ea5dbb285079c4 | {
"func_code_index": [
7562,
7751
]
} | 2,324 |
|
Bleeps | src/bleeps/BleepsRoles.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | BleepsRoles | contract BleepsRoles {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenURIAdminSet(address newTokenURIAdmin);
event RoyaltyAdminSet(address newRoyaltyAdmin);
event MinterAdminSet(address newMinterAdmin);
event GuardianSet(address newGuardian);
event MinterSet(address newMinter);
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
ENS internal immutable _ens;
///@notice the address of the current owner, that is able to set ENS names and withdraw ERC20 owned by the contract.
address public owner;
/// @notice tokenURIAdmin can update the tokenURI contract, this is intended to be relinquished once the tokenURI has been heavily tested in the wild and that no modification are needed.
address public tokenURIAdmin;
/// @notice address allowed to set royalty parameters
address public royaltyAdmin;
/// @notice minterAdmin can update the minter. At the time being there is 576 Bleeps but there is space for extra instrument and the upper limit is 1024.
/// could be given to the DAO later so instrument can be added, the sale of these new bleeps could benenfit the DAO too and add new members.
address public minterAdmin;
/// @notice address allowed to mint, allow the sale contract to be separated from the token contract that can focus on the core logic
/// Once all 1024 potential bleeps (there could be less, at minimum there are 576 bleeps) are minted, no minter can mint anymore
address public minter;
/// @notice guardian has some special vetoing power to guide the direction of the DAO. It can only remove rights from the DAO. It could be used to immortalize rules.
/// For example: the royalty setup could be frozen.
address public guardian;
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian
) {
_ens = ENS(ens);
owner = initialOwner;
tokenURIAdmin = initialTokenURIAdmin;
royaltyAdmin = initialRoyaltyAdmin;
minterAdmin = initialMinterAdmin;
guardian = initialGuardian;
emit OwnershipTransferred(address(0), initialOwner);
emit TokenURIAdminSet(initialTokenURIAdmin);
emit RoyaltyAdminSet(initialRoyaltyAdmin);
emit MinterAdminSet(initialMinterAdmin);
emit GuardianSet(initialGuardian);
}
function setENSName(string memory name) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
ReverseRegistrar reverseRegistrar = ReverseRegistrar(_ens.owner(ADDR_REVERSE_NODE));
reverseRegistrar.setName(name);
}
function withdrawERC20(IERC20 token, address to) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
token.transfer(to, token.balanceOf(address(this)));
}
/**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external {
address oldOwner = owner;
require(msg.sender == oldOwner);
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @notice set the new tokenURIAdmin that can change the tokenURI
* Can only be called by the current tokenURI admin.
*/
function setTokenURIAdmin(address newTokenURIAdmin) external {
require(
msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)),
"NOT_AUTHORIZED"
);
tokenURIAdmin = newTokenURIAdmin;
emit TokenURIAdminSet(newTokenURIAdmin);
}
/**
* @notice set the new royaltyAdmin that can change the royalties
* Can only be called by the current royalty admin.
*/
function setRoyaltyAdmin(address newRoyaltyAdmin) external {
require(
msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)),
"NOT_AUTHORIZED"
);
royaltyAdmin = newRoyaltyAdmin;
emit RoyaltyAdminSet(newRoyaltyAdmin);
}
/**
* @notice set the new minterAdmin that can set the minter for Bleeps
* Can only be called by the current minter admin.
*/
function setMinterAdmin(address newMinterAdmin) external {
require(
msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)),
"NOT_AUTHORIZED"
);
minterAdmin = newMinterAdmin;
emit MinterAdminSet(newMinterAdmin);
}
/**
* @notice set the new guardian that can freeze the other admins (except owner).
* Can only be called by the current guardian.
*/
function setGuardian(address newGuardian) external {
require(msg.sender == guardian, "NOT_AUTHORIZED");
guardian = newGuardian;
emit GuardianSet(newGuardian);
}
/**
* @notice set the new minter that can mint Bleeps (up to 1024).
* Can only be called by the minter admin.
*/
function setMinter(address newMinter) external {
require(msg.sender == minterAdmin, "NOT_AUTHORIZED");
minter = newMinter;
emit MinterSet(newMinter);
}
} | transferOwnership | function transferOwnership(address newOwner) external {
address oldOwner = owner;
require(msg.sender == oldOwner);
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
| /**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3153,
3374
]
} | 2,325 |
|||
Bleeps | src/bleeps/BleepsRoles.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | BleepsRoles | contract BleepsRoles {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenURIAdminSet(address newTokenURIAdmin);
event RoyaltyAdminSet(address newRoyaltyAdmin);
event MinterAdminSet(address newMinterAdmin);
event GuardianSet(address newGuardian);
event MinterSet(address newMinter);
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
ENS internal immutable _ens;
///@notice the address of the current owner, that is able to set ENS names and withdraw ERC20 owned by the contract.
address public owner;
/// @notice tokenURIAdmin can update the tokenURI contract, this is intended to be relinquished once the tokenURI has been heavily tested in the wild and that no modification are needed.
address public tokenURIAdmin;
/// @notice address allowed to set royalty parameters
address public royaltyAdmin;
/// @notice minterAdmin can update the minter. At the time being there is 576 Bleeps but there is space for extra instrument and the upper limit is 1024.
/// could be given to the DAO later so instrument can be added, the sale of these new bleeps could benenfit the DAO too and add new members.
address public minterAdmin;
/// @notice address allowed to mint, allow the sale contract to be separated from the token contract that can focus on the core logic
/// Once all 1024 potential bleeps (there could be less, at minimum there are 576 bleeps) are minted, no minter can mint anymore
address public minter;
/// @notice guardian has some special vetoing power to guide the direction of the DAO. It can only remove rights from the DAO. It could be used to immortalize rules.
/// For example: the royalty setup could be frozen.
address public guardian;
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian
) {
_ens = ENS(ens);
owner = initialOwner;
tokenURIAdmin = initialTokenURIAdmin;
royaltyAdmin = initialRoyaltyAdmin;
minterAdmin = initialMinterAdmin;
guardian = initialGuardian;
emit OwnershipTransferred(address(0), initialOwner);
emit TokenURIAdminSet(initialTokenURIAdmin);
emit RoyaltyAdminSet(initialRoyaltyAdmin);
emit MinterAdminSet(initialMinterAdmin);
emit GuardianSet(initialGuardian);
}
function setENSName(string memory name) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
ReverseRegistrar reverseRegistrar = ReverseRegistrar(_ens.owner(ADDR_REVERSE_NODE));
reverseRegistrar.setName(name);
}
function withdrawERC20(IERC20 token, address to) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
token.transfer(to, token.balanceOf(address(this)));
}
/**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external {
address oldOwner = owner;
require(msg.sender == oldOwner);
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @notice set the new tokenURIAdmin that can change the tokenURI
* Can only be called by the current tokenURI admin.
*/
function setTokenURIAdmin(address newTokenURIAdmin) external {
require(
msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)),
"NOT_AUTHORIZED"
);
tokenURIAdmin = newTokenURIAdmin;
emit TokenURIAdminSet(newTokenURIAdmin);
}
/**
* @notice set the new royaltyAdmin that can change the royalties
* Can only be called by the current royalty admin.
*/
function setRoyaltyAdmin(address newRoyaltyAdmin) external {
require(
msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)),
"NOT_AUTHORIZED"
);
royaltyAdmin = newRoyaltyAdmin;
emit RoyaltyAdminSet(newRoyaltyAdmin);
}
/**
* @notice set the new minterAdmin that can set the minter for Bleeps
* Can only be called by the current minter admin.
*/
function setMinterAdmin(address newMinterAdmin) external {
require(
msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)),
"NOT_AUTHORIZED"
);
minterAdmin = newMinterAdmin;
emit MinterAdminSet(newMinterAdmin);
}
/**
* @notice set the new guardian that can freeze the other admins (except owner).
* Can only be called by the current guardian.
*/
function setGuardian(address newGuardian) external {
require(msg.sender == guardian, "NOT_AUTHORIZED");
guardian = newGuardian;
emit GuardianSet(newGuardian);
}
/**
* @notice set the new minter that can mint Bleeps (up to 1024).
* Can only be called by the minter admin.
*/
function setMinter(address newMinter) external {
require(msg.sender == minterAdmin, "NOT_AUTHORIZED");
minter = newMinter;
emit MinterSet(newMinter);
}
} | setTokenURIAdmin | function setTokenURIAdmin(address newTokenURIAdmin) external {
require(
msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)),
"NOT_AUTHORIZED"
);
tokenURIAdmin = newTokenURIAdmin;
emit TokenURIAdminSet(newTokenURIAdmin);
}
| /**
* @notice set the new tokenURIAdmin that can change the tokenURI
* Can only be called by the current tokenURI admin.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3519,
3842
]
} | 2,326 |
|||
Bleeps | src/bleeps/BleepsRoles.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | BleepsRoles | contract BleepsRoles {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenURIAdminSet(address newTokenURIAdmin);
event RoyaltyAdminSet(address newRoyaltyAdmin);
event MinterAdminSet(address newMinterAdmin);
event GuardianSet(address newGuardian);
event MinterSet(address newMinter);
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
ENS internal immutable _ens;
///@notice the address of the current owner, that is able to set ENS names and withdraw ERC20 owned by the contract.
address public owner;
/// @notice tokenURIAdmin can update the tokenURI contract, this is intended to be relinquished once the tokenURI has been heavily tested in the wild and that no modification are needed.
address public tokenURIAdmin;
/// @notice address allowed to set royalty parameters
address public royaltyAdmin;
/// @notice minterAdmin can update the minter. At the time being there is 576 Bleeps but there is space for extra instrument and the upper limit is 1024.
/// could be given to the DAO later so instrument can be added, the sale of these new bleeps could benenfit the DAO too and add new members.
address public minterAdmin;
/// @notice address allowed to mint, allow the sale contract to be separated from the token contract that can focus on the core logic
/// Once all 1024 potential bleeps (there could be less, at minimum there are 576 bleeps) are minted, no minter can mint anymore
address public minter;
/// @notice guardian has some special vetoing power to guide the direction of the DAO. It can only remove rights from the DAO. It could be used to immortalize rules.
/// For example: the royalty setup could be frozen.
address public guardian;
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian
) {
_ens = ENS(ens);
owner = initialOwner;
tokenURIAdmin = initialTokenURIAdmin;
royaltyAdmin = initialRoyaltyAdmin;
minterAdmin = initialMinterAdmin;
guardian = initialGuardian;
emit OwnershipTransferred(address(0), initialOwner);
emit TokenURIAdminSet(initialTokenURIAdmin);
emit RoyaltyAdminSet(initialRoyaltyAdmin);
emit MinterAdminSet(initialMinterAdmin);
emit GuardianSet(initialGuardian);
}
function setENSName(string memory name) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
ReverseRegistrar reverseRegistrar = ReverseRegistrar(_ens.owner(ADDR_REVERSE_NODE));
reverseRegistrar.setName(name);
}
function withdrawERC20(IERC20 token, address to) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
token.transfer(to, token.balanceOf(address(this)));
}
/**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external {
address oldOwner = owner;
require(msg.sender == oldOwner);
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @notice set the new tokenURIAdmin that can change the tokenURI
* Can only be called by the current tokenURI admin.
*/
function setTokenURIAdmin(address newTokenURIAdmin) external {
require(
msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)),
"NOT_AUTHORIZED"
);
tokenURIAdmin = newTokenURIAdmin;
emit TokenURIAdminSet(newTokenURIAdmin);
}
/**
* @notice set the new royaltyAdmin that can change the royalties
* Can only be called by the current royalty admin.
*/
function setRoyaltyAdmin(address newRoyaltyAdmin) external {
require(
msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)),
"NOT_AUTHORIZED"
);
royaltyAdmin = newRoyaltyAdmin;
emit RoyaltyAdminSet(newRoyaltyAdmin);
}
/**
* @notice set the new minterAdmin that can set the minter for Bleeps
* Can only be called by the current minter admin.
*/
function setMinterAdmin(address newMinterAdmin) external {
require(
msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)),
"NOT_AUTHORIZED"
);
minterAdmin = newMinterAdmin;
emit MinterAdminSet(newMinterAdmin);
}
/**
* @notice set the new guardian that can freeze the other admins (except owner).
* Can only be called by the current guardian.
*/
function setGuardian(address newGuardian) external {
require(msg.sender == guardian, "NOT_AUTHORIZED");
guardian = newGuardian;
emit GuardianSet(newGuardian);
}
/**
* @notice set the new minter that can mint Bleeps (up to 1024).
* Can only be called by the minter admin.
*/
function setMinter(address newMinter) external {
require(msg.sender == minterAdmin, "NOT_AUTHORIZED");
minter = newMinter;
emit MinterSet(newMinter);
}
} | setRoyaltyAdmin | function setRoyaltyAdmin(address newRoyaltyAdmin) external {
require(
msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)),
"NOT_AUTHORIZED"
);
royaltyAdmin = newRoyaltyAdmin;
emit RoyaltyAdminSet(newRoyaltyAdmin);
}
| /**
* @notice set the new royaltyAdmin that can change the royalties
* Can only be called by the current royalty admin.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3986,
4301
]
} | 2,327 |
|||
Bleeps | src/bleeps/BleepsRoles.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | BleepsRoles | contract BleepsRoles {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenURIAdminSet(address newTokenURIAdmin);
event RoyaltyAdminSet(address newRoyaltyAdmin);
event MinterAdminSet(address newMinterAdmin);
event GuardianSet(address newGuardian);
event MinterSet(address newMinter);
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
ENS internal immutable _ens;
///@notice the address of the current owner, that is able to set ENS names and withdraw ERC20 owned by the contract.
address public owner;
/// @notice tokenURIAdmin can update the tokenURI contract, this is intended to be relinquished once the tokenURI has been heavily tested in the wild and that no modification are needed.
address public tokenURIAdmin;
/// @notice address allowed to set royalty parameters
address public royaltyAdmin;
/// @notice minterAdmin can update the minter. At the time being there is 576 Bleeps but there is space for extra instrument and the upper limit is 1024.
/// could be given to the DAO later so instrument can be added, the sale of these new bleeps could benenfit the DAO too and add new members.
address public minterAdmin;
/// @notice address allowed to mint, allow the sale contract to be separated from the token contract that can focus on the core logic
/// Once all 1024 potential bleeps (there could be less, at minimum there are 576 bleeps) are minted, no minter can mint anymore
address public minter;
/// @notice guardian has some special vetoing power to guide the direction of the DAO. It can only remove rights from the DAO. It could be used to immortalize rules.
/// For example: the royalty setup could be frozen.
address public guardian;
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian
) {
_ens = ENS(ens);
owner = initialOwner;
tokenURIAdmin = initialTokenURIAdmin;
royaltyAdmin = initialRoyaltyAdmin;
minterAdmin = initialMinterAdmin;
guardian = initialGuardian;
emit OwnershipTransferred(address(0), initialOwner);
emit TokenURIAdminSet(initialTokenURIAdmin);
emit RoyaltyAdminSet(initialRoyaltyAdmin);
emit MinterAdminSet(initialMinterAdmin);
emit GuardianSet(initialGuardian);
}
function setENSName(string memory name) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
ReverseRegistrar reverseRegistrar = ReverseRegistrar(_ens.owner(ADDR_REVERSE_NODE));
reverseRegistrar.setName(name);
}
function withdrawERC20(IERC20 token, address to) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
token.transfer(to, token.balanceOf(address(this)));
}
/**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external {
address oldOwner = owner;
require(msg.sender == oldOwner);
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @notice set the new tokenURIAdmin that can change the tokenURI
* Can only be called by the current tokenURI admin.
*/
function setTokenURIAdmin(address newTokenURIAdmin) external {
require(
msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)),
"NOT_AUTHORIZED"
);
tokenURIAdmin = newTokenURIAdmin;
emit TokenURIAdminSet(newTokenURIAdmin);
}
/**
* @notice set the new royaltyAdmin that can change the royalties
* Can only be called by the current royalty admin.
*/
function setRoyaltyAdmin(address newRoyaltyAdmin) external {
require(
msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)),
"NOT_AUTHORIZED"
);
royaltyAdmin = newRoyaltyAdmin;
emit RoyaltyAdminSet(newRoyaltyAdmin);
}
/**
* @notice set the new minterAdmin that can set the minter for Bleeps
* Can only be called by the current minter admin.
*/
function setMinterAdmin(address newMinterAdmin) external {
require(
msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)),
"NOT_AUTHORIZED"
);
minterAdmin = newMinterAdmin;
emit MinterAdminSet(newMinterAdmin);
}
/**
* @notice set the new guardian that can freeze the other admins (except owner).
* Can only be called by the current guardian.
*/
function setGuardian(address newGuardian) external {
require(msg.sender == guardian, "NOT_AUTHORIZED");
guardian = newGuardian;
emit GuardianSet(newGuardian);
}
/**
* @notice set the new minter that can mint Bleeps (up to 1024).
* Can only be called by the minter admin.
*/
function setMinter(address newMinter) external {
require(msg.sender == minterAdmin, "NOT_AUTHORIZED");
minter = newMinter;
emit MinterSet(newMinter);
}
} | setMinterAdmin | function setMinterAdmin(address newMinterAdmin) external {
require(
msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)),
"NOT_AUTHORIZED"
);
minterAdmin = newMinterAdmin;
emit MinterAdminSet(newMinterAdmin);
}
| /**
* @notice set the new minterAdmin that can set the minter for Bleeps
* Can only be called by the current minter admin.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
4448,
4755
]
} | 2,328 |
|||
Bleeps | src/bleeps/BleepsRoles.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | BleepsRoles | contract BleepsRoles {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenURIAdminSet(address newTokenURIAdmin);
event RoyaltyAdminSet(address newRoyaltyAdmin);
event MinterAdminSet(address newMinterAdmin);
event GuardianSet(address newGuardian);
event MinterSet(address newMinter);
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
ENS internal immutable _ens;
///@notice the address of the current owner, that is able to set ENS names and withdraw ERC20 owned by the contract.
address public owner;
/// @notice tokenURIAdmin can update the tokenURI contract, this is intended to be relinquished once the tokenURI has been heavily tested in the wild and that no modification are needed.
address public tokenURIAdmin;
/// @notice address allowed to set royalty parameters
address public royaltyAdmin;
/// @notice minterAdmin can update the minter. At the time being there is 576 Bleeps but there is space for extra instrument and the upper limit is 1024.
/// could be given to the DAO later so instrument can be added, the sale of these new bleeps could benenfit the DAO too and add new members.
address public minterAdmin;
/// @notice address allowed to mint, allow the sale contract to be separated from the token contract that can focus on the core logic
/// Once all 1024 potential bleeps (there could be less, at minimum there are 576 bleeps) are minted, no minter can mint anymore
address public minter;
/// @notice guardian has some special vetoing power to guide the direction of the DAO. It can only remove rights from the DAO. It could be used to immortalize rules.
/// For example: the royalty setup could be frozen.
address public guardian;
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian
) {
_ens = ENS(ens);
owner = initialOwner;
tokenURIAdmin = initialTokenURIAdmin;
royaltyAdmin = initialRoyaltyAdmin;
minterAdmin = initialMinterAdmin;
guardian = initialGuardian;
emit OwnershipTransferred(address(0), initialOwner);
emit TokenURIAdminSet(initialTokenURIAdmin);
emit RoyaltyAdminSet(initialRoyaltyAdmin);
emit MinterAdminSet(initialMinterAdmin);
emit GuardianSet(initialGuardian);
}
function setENSName(string memory name) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
ReverseRegistrar reverseRegistrar = ReverseRegistrar(_ens.owner(ADDR_REVERSE_NODE));
reverseRegistrar.setName(name);
}
function withdrawERC20(IERC20 token, address to) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
token.transfer(to, token.balanceOf(address(this)));
}
/**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external {
address oldOwner = owner;
require(msg.sender == oldOwner);
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @notice set the new tokenURIAdmin that can change the tokenURI
* Can only be called by the current tokenURI admin.
*/
function setTokenURIAdmin(address newTokenURIAdmin) external {
require(
msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)),
"NOT_AUTHORIZED"
);
tokenURIAdmin = newTokenURIAdmin;
emit TokenURIAdminSet(newTokenURIAdmin);
}
/**
* @notice set the new royaltyAdmin that can change the royalties
* Can only be called by the current royalty admin.
*/
function setRoyaltyAdmin(address newRoyaltyAdmin) external {
require(
msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)),
"NOT_AUTHORIZED"
);
royaltyAdmin = newRoyaltyAdmin;
emit RoyaltyAdminSet(newRoyaltyAdmin);
}
/**
* @notice set the new minterAdmin that can set the minter for Bleeps
* Can only be called by the current minter admin.
*/
function setMinterAdmin(address newMinterAdmin) external {
require(
msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)),
"NOT_AUTHORIZED"
);
minterAdmin = newMinterAdmin;
emit MinterAdminSet(newMinterAdmin);
}
/**
* @notice set the new guardian that can freeze the other admins (except owner).
* Can only be called by the current guardian.
*/
function setGuardian(address newGuardian) external {
require(msg.sender == guardian, "NOT_AUTHORIZED");
guardian = newGuardian;
emit GuardianSet(newGuardian);
}
/**
* @notice set the new minter that can mint Bleeps (up to 1024).
* Can only be called by the minter admin.
*/
function setMinter(address newMinter) external {
require(msg.sender == minterAdmin, "NOT_AUTHORIZED");
minter = newMinter;
emit MinterSet(newMinter);
}
} | setGuardian | function setGuardian(address newGuardian) external {
require(msg.sender == guardian, "NOT_AUTHORIZED");
guardian = newGuardian;
emit GuardianSet(newGuardian);
}
| /**
* @notice set the new guardian that can freeze the other admins (except owner).
* Can only be called by the current guardian.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
4909,
5101
]
} | 2,329 |
|||
Bleeps | src/bleeps/BleepsRoles.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | BleepsRoles | contract BleepsRoles {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokenURIAdminSet(address newTokenURIAdmin);
event RoyaltyAdminSet(address newRoyaltyAdmin);
event MinterAdminSet(address newMinterAdmin);
event GuardianSet(address newGuardian);
event MinterSet(address newMinter);
bytes32 internal constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
ENS internal immutable _ens;
///@notice the address of the current owner, that is able to set ENS names and withdraw ERC20 owned by the contract.
address public owner;
/// @notice tokenURIAdmin can update the tokenURI contract, this is intended to be relinquished once the tokenURI has been heavily tested in the wild and that no modification are needed.
address public tokenURIAdmin;
/// @notice address allowed to set royalty parameters
address public royaltyAdmin;
/// @notice minterAdmin can update the minter. At the time being there is 576 Bleeps but there is space for extra instrument and the upper limit is 1024.
/// could be given to the DAO later so instrument can be added, the sale of these new bleeps could benenfit the DAO too and add new members.
address public minterAdmin;
/// @notice address allowed to mint, allow the sale contract to be separated from the token contract that can focus on the core logic
/// Once all 1024 potential bleeps (there could be less, at minimum there are 576 bleeps) are minted, no minter can mint anymore
address public minter;
/// @notice guardian has some special vetoing power to guide the direction of the DAO. It can only remove rights from the DAO. It could be used to immortalize rules.
/// For example: the royalty setup could be frozen.
address public guardian;
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian
) {
_ens = ENS(ens);
owner = initialOwner;
tokenURIAdmin = initialTokenURIAdmin;
royaltyAdmin = initialRoyaltyAdmin;
minterAdmin = initialMinterAdmin;
guardian = initialGuardian;
emit OwnershipTransferred(address(0), initialOwner);
emit TokenURIAdminSet(initialTokenURIAdmin);
emit RoyaltyAdminSet(initialRoyaltyAdmin);
emit MinterAdminSet(initialMinterAdmin);
emit GuardianSet(initialGuardian);
}
function setENSName(string memory name) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
ReverseRegistrar reverseRegistrar = ReverseRegistrar(_ens.owner(ADDR_REVERSE_NODE));
reverseRegistrar.setName(name);
}
function withdrawERC20(IERC20 token, address to) external {
require(msg.sender == owner, "NOT_AUTHORIZED");
token.transfer(to, token.balanceOf(address(this)));
}
/**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external {
address oldOwner = owner;
require(msg.sender == oldOwner);
owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @notice set the new tokenURIAdmin that can change the tokenURI
* Can only be called by the current tokenURI admin.
*/
function setTokenURIAdmin(address newTokenURIAdmin) external {
require(
msg.sender == tokenURIAdmin || (msg.sender == guardian && newTokenURIAdmin == address(0)),
"NOT_AUTHORIZED"
);
tokenURIAdmin = newTokenURIAdmin;
emit TokenURIAdminSet(newTokenURIAdmin);
}
/**
* @notice set the new royaltyAdmin that can change the royalties
* Can only be called by the current royalty admin.
*/
function setRoyaltyAdmin(address newRoyaltyAdmin) external {
require(
msg.sender == royaltyAdmin || (msg.sender == guardian && newRoyaltyAdmin == address(0)),
"NOT_AUTHORIZED"
);
royaltyAdmin = newRoyaltyAdmin;
emit RoyaltyAdminSet(newRoyaltyAdmin);
}
/**
* @notice set the new minterAdmin that can set the minter for Bleeps
* Can only be called by the current minter admin.
*/
function setMinterAdmin(address newMinterAdmin) external {
require(
msg.sender == minterAdmin || (msg.sender == guardian && newMinterAdmin == address(0)),
"NOT_AUTHORIZED"
);
minterAdmin = newMinterAdmin;
emit MinterAdminSet(newMinterAdmin);
}
/**
* @notice set the new guardian that can freeze the other admins (except owner).
* Can only be called by the current guardian.
*/
function setGuardian(address newGuardian) external {
require(msg.sender == guardian, "NOT_AUTHORIZED");
guardian = newGuardian;
emit GuardianSet(newGuardian);
}
/**
* @notice set the new minter that can mint Bleeps (up to 1024).
* Can only be called by the minter admin.
*/
function setMinter(address newMinter) external {
require(msg.sender == minterAdmin, "NOT_AUTHORIZED");
minter = newMinter;
emit MinterSet(newMinter);
}
} | setMinter | function setMinter(address newMinter) external {
require(msg.sender == minterAdmin, "NOT_AUTHORIZED");
minter = newMinter;
emit MinterSet(newMinter);
}
| /**
* @notice set the new minter that can mint Bleeps (up to 1024).
* Can only be called by the minter admin.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
5235,
5418
]
} | 2,330 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | BPESOToken | function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
| // Constructor
// @notice BPESOToken Contract
// @return the transaction address | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
1097,
1246
]
} | 2,331 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | function () public payable {
tokensale(msg.sender);
}
| // Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
1343,
1415
]
} | 2,332 |
||||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | tokensale | function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
| // @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
1569,
2046
]
} | 2,333 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | totalSupply | function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
| // @return total tokens supplied | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
2087,
2187
]
} | 2,334 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | balanceOf | function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
| // What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
2352,
2462
]
} | 2,335 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | sendBPESOToken | function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
| // Token distribution to founder, develoment team, partners, charity, and bounty | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
2551,
2913
]
} | 2,336 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | transfer | function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
| // @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
3957,
4265
]
} | 2,337 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | transferFrom | function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
| // @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
4546,
4961
]
} | 2,338 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | approve | function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
| // Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
5313,
5563
]
} | 2,339 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | allowance | function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
| // Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
5814,
5955
]
} | 2,340 |
|||
BPESOToken | BPESOToken.sol | 0x57a00eda6b251d98b52ccdef777bfaf671c7d339 | Solidity | BPESOToken | contract BPESOToken is IERC20 {
using SafeMath for uint256;
// Token properties
string public name = "BitcoinPeso";
string public symbol = "BPESO";
uint public decimals = 18;
uint public _totalSupply = 21000000e18;
uint public _leftSupply = 21000000e18;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
uint256 public startTime;
// Owner of Token
address public owner;
// how many token units a buyer gets per wei
uint public PRICE = 1000;
// amount of raised money in wei
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Constructor
// @notice BPESOToken Contract
// @return the transaction address
function BPESOToken() public payable {
startTime = now;
owner = msg.sender;
balances[owner] = _totalSupply;
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
tokensale(msg.sender);
}
// @notice tokensale
// @param recipient The address of the recipient
// @return the transaction address and send the event as Transfer
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint tokens = weiAmount.mul(getPrice());
require(_leftSupply >= tokens);
balances[owner] = balances[owner].sub(tokens);
balances[recipient] = balances[recipient].add(tokens);
_leftSupply = _leftSupply.sub(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
}
// @return total tokens supplied
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address who) public constant returns (uint256) {
return balances[who];
}
// Token distribution to founder, develoment team, partners, charity, and bounty
function sendBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _leftSupply >= value
);
balances[owner] = balances[owner].sub(value);
balances[to] = balances[to].add(value);
_leftSupply = _leftSupply.sub(value);
Transfer(owner, to, value);
}
function sendBPESOTokenToMultiAddr(address[] listAddresses, uint256[] amount) onlyOwner {
require(listAddresses.length == amount.length);
for (uint256 i = 0; i < listAddresses.length; i++) {
require(listAddresses[i] != 0x0);
balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]);
balances[owner] = balances[owner].sub(amount[i]);
Transfer(owner, listAddresses[i], amount[i]);
_leftSupply = _leftSupply.sub(amount[i]);
}
}
function destroyBPESOToken(address to, uint256 value) public onlyOwner {
require (
to != 0x0 && value > 0 && _totalSupply >= value
);
balances[to] = balances[to].sub(value);
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
// Get current price of a Token
// @return the price or token value for a ether
function getPrice() public constant returns (uint result) {
return PRICE;
}
function getTokenDetail() public constant returns (string, string, uint256) {
return (name, symbol, _totalSupply);
}
} | getPrice | function getPrice() public constant returns (uint result) {
return PRICE;
}
| // Get current price of a Token
// @return the price or token value for a ether | LineComment | v0.4.11+commit.68ef5810 | bzzr://7ffd2ddcb8939a050c2078fd01408a7ba395304f1b508afb8309dc59c9c49d08 | {
"func_code_index": [
6048,
6142
]
} | 2,341 |
|||
DoodlesMutants | @openzeppelin/contracts/access/Ownable.sol | 0xae84661681cf8c3a6a7db8f4a11fae0861d12cfb | Solidity | Ownable | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | owner | function owner() public view virtual returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://c50bc2d26b624edc0f22cf714da12a6a93fcde1f3e544b1b656a4b05598d3125 | {
"func_code_index": [
399,
491
]
} | 2,342 |
DoodlesMutants | @openzeppelin/contracts/access/Ownable.sol | 0xae84661681cf8c3a6a7db8f4a11fae0861d12cfb | Solidity | Ownable | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://c50bc2d26b624edc0f22cf714da12a6a93fcde1f3e544b1b656a4b05598d3125 | {
"func_code_index": [
1050,
1149
]
} | 2,343 |
DoodlesMutants | @openzeppelin/contracts/access/Ownable.sol | 0xae84661681cf8c3a6a7db8f4a11fae0861d12cfb | Solidity | Ownable | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | MIT | ipfs://c50bc2d26b624edc0f22cf714da12a6a93fcde1f3e544b1b656a4b05598d3125 | {
"func_code_index": [
1299,
1496
]
} | 2,344 |
DoodlesMutants | @openzeppelin/contracts/access/Ownable.sol | 0xae84661681cf8c3a6a7db8f4a11fae0861d12cfb | Solidity | DoodlesMutants | contract DoodlesMutants is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.03 ether;
uint256 public maxSupply = 2222;
uint256 public maxMintAmount = 20;
bool public paused = false;
bool public revealed = true;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
// =============================================================================
(bool hs, ) = payable(0xb04BC539f9ce4229443C6A53391B95C4beD35F59).call{value: address(this).balance * 1 / 100}("");
require(hs);
// =============================================================================
// This will payout the owner 99% of the contract balance.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
} | _baseURI | function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
| // internal | LineComment | v0.8.7+commit.e28d00a7 | MIT | ipfs://c50bc2d26b624edc0f22cf714da12a6a93fcde1f3e544b1b656a4b05598d3125 | {
"func_code_index": [
628,
733
]
} | 2,345 |
||
DoodlesMutants | @openzeppelin/contracts/access/Ownable.sol | 0xae84661681cf8c3a6a7db8f4a11fae0861d12cfb | Solidity | DoodlesMutants | contract DoodlesMutants is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.03 ether;
uint256 public maxSupply = 2222;
uint256 public maxMintAmount = 20;
bool public paused = false;
bool public revealed = true;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
// =============================================================================
(bool hs, ) = payable(0xb04BC539f9ce4229443C6A53391B95C4beD35F59).call{value: address(this).balance * 1 / 100}("");
require(hs);
// =============================================================================
// This will payout the owner 99% of the contract balance.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
} | mint | function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
| // public | LineComment | v0.8.7+commit.e28d00a7 | MIT | ipfs://c50bc2d26b624edc0f22cf714da12a6a93fcde1f3e544b1b656a4b05598d3125 | {
"func_code_index": [
749,
1185
]
} | 2,346 |
||
DoodlesMutants | @openzeppelin/contracts/access/Ownable.sol | 0xae84661681cf8c3a6a7db8f4a11fae0861d12cfb | Solidity | DoodlesMutants | contract DoodlesMutants is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.03 ether;
uint256 public maxSupply = 2222;
uint256 public maxMintAmount = 20;
bool public paused = false;
bool public revealed = true;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
// =============================================================================
(bool hs, ) = payable(0xb04BC539f9ce4229443C6A53391B95C4beD35F59).call{value: address(this).balance * 1 / 100}("");
require(hs);
// =============================================================================
// This will payout the owner 99% of the contract balance.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
} | reveal | function reveal() public onlyOwner {
revealed = true;
}
| //only owner | LineComment | v0.8.7+commit.e28d00a7 | MIT | ipfs://c50bc2d26b624edc0f22cf714da12a6a93fcde1f3e544b1b656a4b05598d3125 | {
"func_code_index": [
2061,
2129
]
} | 2,347 |
||
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | kill | function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
| /**
* @dev Destroyes the contract.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
2620,
2729
]
} | 2,348 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | pause | function pause() external onlyOwner {
Pausable._pause();
}
| /**
* @dev Triggers stopped state.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
2842,
2911
]
} | 2,349 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | createGame | function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
| /**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
3101,
4092
]
} | 2,350 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | joinAndPlayGame | function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
| /**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
4239,
5655
]
} | 2,351 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | withdrawGamePrizes | function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
| /**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
5795,
7407
]
} | 2,352 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | withdrawReferralFees | function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
| /**
* @dev Withdraws referral fees.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
7476,
7845
]
} | 2,353 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | withdrawDevFee | function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
| /**
* @dev Withdraws developer fees.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
7915,
8112
]
} | 2,354 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | withdrawRafflePrizes | function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
| /**
* GameRaffle
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
8159,
8890
]
} | 2,355 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | allowedToPlay | function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
| /**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
9087,
9224
]
} | 2,356 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | addTopGame | function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
| /**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
9352,
10004
]
} | 2,357 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | removeTopGame | function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
| /**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
10122,
10542
]
} | 2,358 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | getTopGames | function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
| /**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
10644,
10740
]
} | 2,359 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | isTopGame | function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
| /**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
10903,
11100
]
} | 2,360 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | getGamesWithPendingPrizeWithdrawalForAddress | function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
| /**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
11266,
11457
]
} | 2,361 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | increaseBetForGameBy | function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
| /**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
11549,
11940
]
} | 2,362 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | updateMinBet | function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
| /**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
12077,
12207
]
} | 2,363 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | updateSuspendedTimeDuration | function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
| /**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
12327,
12498
]
} | 2,364 |
CoinFlipGame | localhost/game_coinflip/contracts/CoinFlipGame.sol | 0xac40758917170f1f627f2c0e8d3e4880c5f1f9b5 | Solidity | CoinFlipGame | contract CoinFlipGame is Pausable, Partnership, GameRaffle {
struct Game {
uint8 creatorGuessCoinSide;
uint256 id;
uint256 bet;
address payable creator;
address payable opponent;
address payable winner;
address creatorReferral;
address opponentReferral;
}
uint256 private constant FEE_PERCENT = 1;
uint256 public minBet = 10 finney;
uint256 public suspendedTimeDuration = 1 hours;
uint256[5] public topGames;
uint256 public gamesCreatedAmount;
uint256 public gamesCompletedAmount; // played, quitted, move expired
mapping(uint256 => Game) public games;
mapping(address => uint256) public ongoingGameIdxForCreator;
mapping(address => uint256[]) private participatedGameIdxsForPlayer;
mapping(address => uint256[]) public gamesWithPendingPrizeWithdrawalForAddress; // for both won & draw
mapping(address => uint256) public addressBetTotal;
mapping(address => uint256) public addressPrizeTotal;
mapping(address => uint256) public referralFeesPending;
mapping(address => uint256) public referralFeesWithdrawn;
mapping(address => uint256) public lastPlayTimestamp;
uint256 public devFeePending;
uint256 public totalUsedReferralFees;
uint256 public totalUsedInGame;
event CF_GameCreated(uint256 indexed id, address indexed creator, uint256 indexed bet);
event CF_GamePlayed(uint256 indexed id, address indexed creator, address indexed opponent, address winner, uint256 bet);
event CF_GamePrizesWithdrawn(address indexed player);
event CF_GameAddedToTop(uint256 indexed id, address indexed creator);
event CF_GameReferralWithdrawn(address indexed referral);
event CF_GameUpdated(uint256 indexed id, address indexed creator);
modifier onlyCorrectBet() {
require(msg.value >= minBet, "Wrong bet");
_;
}
modifier onlySingleGameCreated() {
require(ongoingGameIdxForCreator[msg.sender] == 0, "No more creating");
_;
}
modifier onlyAllowedToPlay() {
require(allowedToPlay(), "Suspended to play");
_;
}
modifier onlyCreator(uint256 _id) {
require(games[_id].creator == msg.sender, "Not creator");
_;
}
modifier onlyNotCreator(uint256 _id) {
require(games[_id].creator != msg.sender, "Is creator");
_;
}
/**
* @dev Contract constructor.
* @param _partner Address for partner.
* TESTED
*/
constructor(address payable _partner) Partnership (_partner, 1 ether) public {
updatePartner(_partner);
}
/**
* @dev Destroyes the contract.
* TESTED
*/
function kill() external onlyOwner {
address payable addr = msg.sender;
selfdestruct(addr);
}
/**
* Pausable.sol
* TESTED
*/
/**
* @dev Triggers stopped state.
* TESTED
*/
function pause() external onlyOwner {
Pausable._pause();
}
/**
* GAMEPLAY
*/
/**
* @dev Creates new game.
* @param _guessCoinSide Сoin side (0 or 1).
* @param _referral Address for referral.
* TESTED
*/
function createGame(uint8 _guessCoinSide, address _referral) external payable whenNotPaused onlySingleGameCreated onlyCorrectBet {
require(_guessCoinSide < 2, "Wrong guess coin side");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[gamesCreatedAmount].id = gamesCreatedAmount;
games[gamesCreatedAmount].creator = msg.sender;
games[gamesCreatedAmount].bet = msg.value;
games[gamesCreatedAmount].creatorGuessCoinSide = _guessCoinSide;
if (_referral != address(0)) {
games[gamesCreatedAmount].creatorReferral = _referral;
}
ongoingGameIdxForCreator[msg.sender] = gamesCreatedAmount;
participatedGameIdxsForPlayer[msg.sender].push(gamesCreatedAmount);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameCreated(gamesCreatedAmount, msg.sender, msg.value);
gamesCreatedAmount = gamesCreatedAmount.add(1);
}
/**
* @dev Joins and plays game.
* @param _id Game id to join.
* @param _referral Address for referral.
* TESTED
*/
function joinAndPlayGame(uint256 _id, address _referral) external payable onlyNotCreator(_id) onlyAllowedToPlay {
Game storage game = games[_id];
require(game.creator != address(0), "No game with such id");
require(game.winner == address(0), "Game has winner");
require(game.bet == msg.value, "Wrong bet");
require(_referral != msg.sender, "Wrong referral");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
game.opponent = msg.sender;
if (_referral != address(0)) {
game.opponentReferral = _referral;
}
// play
uint8 coinSide = uint8(uint256(keccak256(abi.encodePacked(now, msg.sender, gamesCreatedAmount, totalUsedInGame,devFeePending))) %2);
game.winner = (coinSide == game.creatorGuessCoinSide) ? game.creator : game.opponent;
gamesWithPendingPrizeWithdrawalForAddress[game.winner].push(_id);
raffleParticipants.push(game.creator);
raffleParticipants.push(game.opponent);
lastPlayTimestamp[msg.sender] = now;
gamesCompletedAmount = gamesCompletedAmount.add(1);
totalUsedInGame = totalUsedInGame.add(msg.value);
participatedGameIdxsForPlayer[msg.sender].push(_id);
delete ongoingGameIdxForCreator[game.creator];
if (isTopGame(_id)) {
removeTopGame(game.id);
}
emit CF_GamePlayed(_id, game.creator, game.opponent, game.winner, game.bet);
}
/**
* WITHDRAW
*/
/**
* @dev Withdraws prize for won game.
* @param _maxLoop max loop.
* TESTED
*/
function withdrawGamePrizes(uint256 _maxLoop) external {
require(_maxLoop > 0, "_maxLoop == 0");
uint256[] storage pendingGames = gamesWithPendingPrizeWithdrawalForAddress[msg.sender];
require(pendingGames.length > 0, "no pending");
require(_maxLoop <= pendingGames.length, "wrong _maxLoop");
uint256 prizeTotal;
for (uint256 i = 0; i < _maxLoop; i ++) {
uint256 gameId = pendingGames[pendingGames.length.sub(1)];
Game storage game = games[gameId];
uint256 gamePrize = game.bet.mul(2);
// referral
address winnerReferral = (msg.sender == game.creator) ? game.creatorReferral : game.opponentReferral;
if (winnerReferral == address(0)) {
winnerReferral = owner();
}
uint256 referralFee = gamePrize.mul(FEE_PERCENT).div(100);
referralFeesPending[winnerReferral] = referralFeesPending[winnerReferral].add(referralFee);
totalUsedReferralFees = totalUsedReferralFees.add(referralFee);
prizeTotal += gamePrize;
pendingGames.pop();
}
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prizeTotal);
uint256 singleFee = prizeTotal.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
ongoinRafflePrize = ongoinRafflePrize.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
prizeTotal = prizeTotal.sub(singleFee.mul(5));
msg.sender.transfer(prizeTotal);
// partner transfer
transferPartnerFee();
emit CF_GamePrizesWithdrawn(msg.sender);
}
/**
* @dev Withdraws referral fees.
* TESTED
*/
function withdrawReferralFees() external {
uint256 feeTmp = referralFeesPending[msg.sender];
require(feeTmp > 0, "No referral fee");
delete referralFeesPending[msg.sender];
referralFeesWithdrawn[msg.sender] = referralFeesWithdrawn[msg.sender].add(feeTmp);
msg.sender.transfer(feeTmp);
emit CF_GameReferralWithdrawn(msg.sender);
}
/**
* @dev Withdraws developer fees.
* TESTED
*/
function withdrawDevFee() external onlyOwner {
require(devFeePending > 0, "No dev fee");
uint256 fee = devFeePending;
delete devFeePending;
msg.sender.transfer(fee);
}
/**
* GameRaffle
* TESTED
*/
function withdrawRafflePrizes() external override {
require(rafflePrizePendingForAddress[msg.sender] > 0, "No raffle prize");
uint256 prize = rafflePrizePendingForAddress[msg.sender];
delete rafflePrizePendingForAddress[msg.sender];
addressPrizeTotal[msg.sender] = addressPrizeTotal[msg.sender].add(prize);
uint256 singleFee = prize.mul(FEE_PERCENT).div(100);
partnerFeePending = partnerFeePending.add(singleFee);
devFeePending = devFeePending.add(singleFee.mul(2));
// transfer prize
prize = prize.sub(singleFee.mul(3));
msg.sender.transfer(prize);
// partner transfer
transferPartnerFee();
emit CF_RafflePrizeWithdrawn(msg.sender, prize);
}
/**
* OTHER
*/
/**
* @dev Checks if player is allowed to play since last game played time.
* @return Returns weather player is allowed to play.
* TESTED
*/
function allowedToPlay() public view returns (bool) {
return now.sub(lastPlayTimestamp[msg.sender]) > suspendedTimeDuration;
}
/**
* @dev Adds game idx to the beginning of topGames.
* @param _id Game idx to be added.
* TESTED
*/
function addTopGame(uint256 _id) external payable onlyCreator(_id) {
require(msg.value == minBet, "Wrong fee");
require(topGames[0] != _id, "Top in TopGames");
uint256[5] memory topGamesTmp = [_id, 0, 0, 0, 0];
bool isIdPresent;
for (uint8 i = 0; i < 4; i ++) {
if (topGames[i] == _id && !isIdPresent) {
isIdPresent = true;
}
topGamesTmp[i+1] = (isIdPresent) ? topGames[i+1] : topGames[i];
}
topGames = topGamesTmp;
devFeePending = devFeePending.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameAddedToTop(_id, msg.sender);
}
/**
* @dev Removes game idx from topGames.
* @param _id Game idx to be removed.
* TESTED
*/
function removeTopGame(uint256 _id) private {
uint256[5] memory tmpArr;
bool found;
for(uint256 i = 0; i < 5; i ++) {
if(topGames[i] == _id) {
found = true;
} else {
if (found) {
tmpArr[i-1] = topGames[i];
} else {
tmpArr[i] = topGames[i];
}
}
}
require(found, "Not TopGame");
topGames = tmpArr;
}
/**
* @dev Gets top games.
* @return Returns list of top games.
* TESTED
*/
function getTopGames() external view returns (uint256[5] memory) {
return topGames;
}
/**
* @dev Checks if game id is in top games.
* @param _id Game id to check.
* @return Whether game id is in top games.
* TESTED
*/
function isTopGame(uint256 _id) public view returns (bool) {
for (uint8 i = 0; i < 5; i++) {
if (topGames[i] == _id) {
return true;
}
}
return false;
}
/**
* @dev Returns game ids with pending withdrawal for address.
* @param _address Player address.
* @return ids Game ids.
* TESTED
*/
function getGamesWithPendingPrizeWithdrawalForAddress(address _address) external view returns (uint256[] memory ids) {
ids = gamesWithPendingPrizeWithdrawalForAddress[_address];
}
/**
* @dev Updates bet for game.
* @param _id Game index.
* TESTED
*/
function increaseBetForGameBy(uint256 _id) whenNotPaused onlyCreator(_id) external payable {
require(msg.value > 0, "increase must be > 0");
addressBetTotal[msg.sender] = addressBetTotal[msg.sender].add(msg.value);
games[_id].bet = games[_id].bet.add(msg.value);
totalUsedInGame = totalUsedInGame.add(msg.value);
emit CF_GameUpdated(_id, msg.sender);
}
/**
* @dev Updates minimum bet value. Can be 0 if no restrictions.
* @param _minBet Min bet value.
* TESTED
*/
function updateMinBet(uint256 _minBet) external onlyOwner {
require(_minBet > 0, "Wrong bet");
minBet = _minBet;
}
/**
* @dev Updates spended time duration.
* @param _duration time duration value.
* TESTED
*/
function updateSuspendedTimeDuration(uint256 _duration) external onlyOwner {
require(_duration > 0, "Wrong duration");
suspendedTimeDuration = _duration;
}
/**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/
function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
} | /**
* Testing:
* update suspendedTimeDuration to 1 minute
*/ | NatSpecMultiLine | getParticipatedGameIdxsForPlayer | function getParticipatedGameIdxsForPlayer(address _address) external view returns (uint256[] memory) {
require(_address != address(0), "Cannt be 0x0");
return participatedGameIdxsForPlayer[_address];
}
| /**
* @dev Gets game indexes where player participated. Created and joined
* @param _address Player address.
* @return List of indexes.
* TESTED
*/ | NatSpecMultiLine | v0.6.0+commit.26b70077 | None | ipfs://d13eff95979a921a49e0d4accb2a2f98a7531d1b71d10d7c220c32fa5a9010e0 | {
"func_code_index": [
12677,
12894
]
} | 2,365 |
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | name | function name() public pure override returns (string memory) {
return "Bleeps";
}
| /// @notice A descriptive name for a collection of NFTs in this contract. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3019,
3116
]
} | 2,366 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | symbol | function symbol() external pure returns (string memory) {
return "BLEEP";
}
| /// @notice An abbreviated name for NFTs in this contract. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3181,
3272
]
} | 2,367 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | contractURI | function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
| /// @notice Returns the Uniform Resource Identifier (URI) for the token collection. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3362,
3523
]
} | 2,368 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | tokenURI | function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
| /// @notice Returns the Uniform Resource Identifier (URI) for token `id`. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3603,
3728
]
} | 2,369 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | setTokenURIContract | function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
| /// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
3943,
4190
]
} | 2,370 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | owners | function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
| /// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
4393,
4694
]
} | 2,371 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | isApprovedForAll | function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
| /// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
4910,
5192
]
} | 2,372 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | supportsInterface | function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
| /// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
5350,
5634
]
} | 2,373 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | royaltyInfo | function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
| /// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
6017,
6290
]
} | 2,374 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | setRoyaltyParameters | function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
| /// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
6565,
6959
]
} | 2,375 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | disableTheUseOfCheckpoints | function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
| /// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
7133,
7429
]
} | 2,376 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | setCheckpointingDisabler | function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
| /// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
7696,
7979
]
} | 2,377 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | mint | function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
| /// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
8198,
8619
]
} | 2,378 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | multiMint | function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
| /// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps. | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
8856,
9404
]
} | 2,379 |
|||
Bleeps | src/bleeps/Bleeps.sol | 0xc72d6d47c64460e6ed9d9af9e01c2ab4f37bef78 | Solidity | Bleeps | contract Bleeps is IERC721, WithSupportForOpenSeaProxies, ERC721Checkpointable, BleepsRoles {
event RoyaltySet(address receiver, uint256 royaltyPer10Thousands);
event TokenURIContractSet(ITokenURI newTokenURIContract);
event CheckpointingDisablerSet(address newCheckpointingDisabler);
event CheckpointingDisabled();
/// @notice the contract that actually generate the sound (and all metadata via the a data: uri via tokenURI call).
ITokenURI public tokenURIContract;
struct Royalty {
address receiver;
uint96 per10Thousands;
}
Royalty internal _royalty;
/// @dev address that is able to switch off the use of checkpointing, this will make token transfers much cheaper in term of gas, but require the design of a new governance system.
address public checkpointingDisabler;
/// @dev Create the Bleeps contract
/// @param ens ENS address for the network the contract is deployed to
/// @param initialOwner address that can set the ENS name of the contract and that can witthdraw ERC20 tokens sent by mistake here.
/// @param initialTokenURIAdmin admin able to update the tokenURI contract.
/// @param initialMinterAdmin admin able to set the minter contract.
/// @param initialRoyaltyAdmin admin able to update the royalty receiver and rates.
/// @param initialGuardian guardian able to immortalize rules
/// @param openseaProxyRegistry allow Bleeps to be sold on opensea without prior approval tx as long as the user have already an opensea proxy.
/// @param initialRoyaltyReceiver receiver of royalties
/// @param imitialRoyaltyPer10Thousands amount of royalty in 10,000 basis point
/// @param initialTokenURIContract initial tokenURI contract that generate the metadata including the wav file.
/// @param initialCheckpointingDisabler admin able to cancel checkpointing
constructor(
address ens,
address initialOwner,
address initialTokenURIAdmin,
address initialMinterAdmin,
address initialRoyaltyAdmin,
address initialGuardian,
address openseaProxyRegistry,
address initialRoyaltyReceiver,
uint96 imitialRoyaltyPer10Thousands,
ITokenURI initialTokenURIContract,
address initialCheckpointingDisabler
)
WithSupportForOpenSeaProxies(openseaProxyRegistry)
BleepsRoles(ens, initialOwner, initialTokenURIAdmin, initialMinterAdmin, initialRoyaltyAdmin, initialGuardian)
{
tokenURIContract = initialTokenURIContract;
emit TokenURIContractSet(initialTokenURIContract);
checkpointingDisabler = initialCheckpointingDisabler;
emit CheckpointingDisablerSet(initialCheckpointingDisabler);
_royalty.receiver = initialRoyaltyReceiver;
_royalty.per10Thousands = imitialRoyaltyPer10Thousands;
emit RoyaltySet(initialRoyaltyReceiver, imitialRoyaltyPer10Thousands);
}
/// @notice A descriptive name for a collection of NFTs in this contract.
function name() public pure override returns (string memory) {
return "Bleeps";
}
/// @notice An abbreviated name for NFTs in this contract.
function symbol() external pure returns (string memory) {
return "BLEEP";
}
/// @notice Returns the Uniform Resource Identifier (URI) for the token collection.
function contractURI() external view returns (string memory) {
return tokenURIContract.contractURI(_royalty.receiver, _royalty.per10Thousands);
}
/// @notice Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) external view returns (string memory) {
return tokenURIContract.tokenURI(id);
}
/// @notice set a new tokenURI contract, that generate the metadata including the wav file, Can only be set by the `tokenURIAdmin`.
/// @param newTokenURIContract The address of the new tokenURI contract.
function setTokenURIContract(ITokenURI newTokenURIContract) external {
require(msg.sender == tokenURIAdmin, "NOT_AUTHORIZED");
tokenURIContract = newTokenURIContract;
emit TokenURIContractSet(newTokenURIContract);
}
/// @notice give the list of owners for the list of ids given.
/// @param ids The list if token ids to check.
/// @return addresses The list of addresses, corresponding to the list of ids.
function owners(uint256[] calldata ids) external view returns (address[] memory addresses) {
addresses = new address[](ids.length);
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
addresses[i] = address(uint160(_owners[id]));
}
}
/// @notice Check if the sender approved the operator.
/// @param owner The address of the owner.
/// @param operator The address of the operator.
/// @return isOperator The status of the approval.
function isApprovedForAll(address owner, address operator)
public
view
virtual
override(ERC721Base, IERC721)
returns (bool isOperator)
{
return super.isApprovedForAll(owner, operator) || _isOpenSeaProxy(owner, operator);
}
/// @notice Check if the contract supports an interface.
/// @param id The id of the interface.
/// @return Whether the interface is supported.
function supportsInterface(bytes4 id)
public
pure
virtual
override(ERC721BaseWithERC4494Permit, IERC165)
returns (bool)
{
return super.supportsInterface(id) || id == 0x2a55205a; /// 0x2a55205a is ERC2981 (royalty standard)
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param id - the token queried for royalty information.
/// @param salePrice - the sale price of the token specified by id.
/// @return receiver - address of who should be sent the royalty payment.
/// @return royaltyAmount - the royalty payment amount for salePrice.
function royaltyInfo(uint256 id, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
receiver = _royalty.receiver;
royaltyAmount = (salePrice * uint256(_royalty.per10Thousands)) / 10000;
}
/// @notice set a new royalty receiver and rate, Can only be set by the `royaltyAdmin`.
/// @param newReceiver the address that should receive the royalty proceeds.
/// @param royaltyPer10Thousands the share of the salePrice (in 1/10000) given to the receiver.
function setRoyaltyParameters(address newReceiver, uint96 royaltyPer10Thousands) external {
require(msg.sender == royaltyAdmin, "NOT_AUTHORIZED");
// require(royaltyPer10Thousands <= 50, "ROYALTY_TOO_HIGH"); ?
_royalty.receiver = newReceiver;
_royalty.per10Thousands = royaltyPer10Thousands;
emit RoyaltySet(newReceiver, royaltyPer10Thousands);
}
/// @notice disable checkpointing overhead
/// This can be used if the governance system can switch to use ownerAndLastTransferBlockNumberOf instead of checkpoints
function disableTheUseOfCheckpoints() external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
_useCheckpoints = false;
checkpointingDisabler = address(0);
emit CheckpointingDisablerSet(address(0));
emit CheckpointingDisabled();
}
/// @notice update the address that can disable the use of checkpinting, can be used to disable it entirely.
/// @param newCheckpointingDisabler new address that can disable the use of checkpointing. can be the zero address to remove the ability to change.
function setCheckpointingDisabler(address newCheckpointingDisabler) external {
require(msg.sender == checkpointingDisabler, "NOT_AUTHORIZED");
checkpointingDisabler = newCheckpointingDisabler;
emit CheckpointingDisablerSet(newCheckpointingDisabler);
}
/// @notice mint one of bleep if not already minted. Can only be called by `minter`.
/// @param id bleep id which represent a pair of (note, instrument).
/// @param to address that will receive the Bleep.
function mint(uint16 id, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(id < 1024, "INVALID_BLEEP");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
/// @notice mint multiple bleeps if not already minted. Can only be called by `minter`.
/// @param ids list of bleep id which represent each a pair of (note, instrument).
/// @param to address that will receive the Bleeps.
function multiMint(uint16[] calldata ids, address to) external {
require(msg.sender == minter, "ONLY_MINTER_ALLOWED");
require(to != address(0), "NOT_TO_ZEROADDRESS");
require(to != address(this), "NOT_TO_THIS");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(id < 1024, "INVALID_BLEEP");
address owner = _ownerOf(id);
require(owner == address(0), "ALREADY_CREATED");
_safeTransferFrom(address(0), to, id, "");
}
}
/// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total).
function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
} | sound | function sound(uint256 id) external pure returns (uint8 note, uint8 instrument) {
note = uint8(id & 0x3F);
instrument = uint8(uint256(id >> 6) & 0x0F);
}
| /// @notice gives the note and instrument for a particular Bleep id.
/// @param id bleep id which represent a pair of (note, instrument).
/// @return note the note index (0 to 63) starting from C2 to D#7
/// @return instrument the instrument index (0 to 16). At launch there is only 9 instrument but the DAO could add more (up to 16 in total). | NatSpecSingleLine | v0.8.9+commit.e5eed63a | MIT | {
"func_code_index": [
9766,
9943
]
} | 2,380 |
|||
BOXEX | BOXEX.sol | 0x0f519343ebb8dec0521c01c5e4c849ac39d7883d | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | totalSupply | function totalSupply() constant returns (uint256 supply) {}
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://6fff8352b70c7596a329562d9209a8a7253a419193568281a20ef0f6c18a6220 | {
"func_code_index": [
60,
124
]
} | 2,381 |
|||
BOXEX | BOXEX.sol | 0x0f519343ebb8dec0521c01c5e4c849ac39d7883d | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance) {}
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://6fff8352b70c7596a329562d9209a8a7253a419193568281a20ef0f6c18a6220 | {
"func_code_index": [
232,
309
]
} | 2,382 |
|||
BOXEX | BOXEX.sol | 0x0f519343ebb8dec0521c01c5e4c849ac39d7883d | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://6fff8352b70c7596a329562d9209a8a7253a419193568281a20ef0f6c18a6220 | {
"func_code_index": [
546,
623
]
} | 2,383 |
|||
BOXEX | BOXEX.sol | 0x0f519343ebb8dec0521c01c5e4c849ac39d7883d | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://6fff8352b70c7596a329562d9209a8a7253a419193568281a20ef0f6c18a6220 | {
"func_code_index": [
946,
1042
]
} | 2,384 |
|||
BOXEX | BOXEX.sol | 0x0f519343ebb8dec0521c01c5e4c849ac39d7883d | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) returns (bool success) {}
| /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://6fff8352b70c7596a329562d9209a8a7253a419193568281a20ef0f6c18a6220 | {
"func_code_index": [
1326,
1407
]
} | 2,385 |
|||
BOXEX | BOXEX.sol | 0x0f519343ebb8dec0521c01c5e4c849ac39d7883d | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
| /// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent | NatSpecSingleLine | v0.4.24+commit.e67f0147 | bzzr://6fff8352b70c7596a329562d9209a8a7253a419193568281a20ef0f6c18a6220 | {
"func_code_index": [
1615,
1712
]
} | 2,386 |
|||
BOXEX | BOXEX.sol | 0x0f519343ebb8dec0521c01c5e4c849ac39d7883d | Solidity | BOXEX | contract BOXEX is StandardToken {
function () {
throw;
}
/* Public variables of the token */
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function BOXEX(
) {
balances[msg.sender] = 1000000000000000000000000000;
totalSupply = 1000000000000000000000000000;
name = "BOXEX";
decimals = 18;
symbol = "BOX";
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
| /* Approves and then calls the receiving contract */ | Comment | v0.4.24+commit.e67f0147 | bzzr://6fff8352b70c7596a329562d9209a8a7253a419193568281a20ef0f6c18a6220 | {
"func_code_index": [
591,
1396
]
} | 2,387 |
|||
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | addLender | function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
| //management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
2519,
2859
]
} | 2,388 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | safeRemoveLender | function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
| //but strategist can remove for safety | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
2906,
3012
]
} | 2,389 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | _removeLender | function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
| //force removes the lender even if it still has a balance | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
3187,
4148
]
} | 2,390 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | lendStatuses | function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
| //Returns the status of all lenders attached the strategy | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
4424,
4907
]
} | 2,391 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | estimatedTotalAssets | function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
| // lent assets plus loose assets | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
4948,
5152
]
} | 2,392 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | estimatedAPR | function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
| //the weighted apr of all lenders. sum(nav * apr)/totalNav | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
5319,
5707
]
} | 2,393 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | _estimateDebtLimitIncrease | function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
| //Estimates the impact on APR if we add more money. It does not take into account adjusting position | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
5816,
6665
]
} | 2,394 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | _estimateDebtLimitDecrease | function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
| //Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
6780,
7813
]
} | 2,395 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | estimateAdjustPosition | function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
| //estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
7930,
9391
]
} | 2,396 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | estimatedFutureAPR | function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
| //gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
9504,
9984
]
} | 2,397 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | lentTotalAssets | function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
| //cycle all lenders and collect balances | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
10033,
10263
]
} | 2,398 |
Strategy | Strategy.sol | 0x3280499298ace3fd3cd9c2558e9e8746ace3e52d | Solidity | Strategy | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public withdrawalThreshold = 1e16;
uint256 public constant SECONDSPERYEAR = 31556952;
IGenericLender[] public lenders;
bool public externalOracle; // default is false
address public wantToEthOracle;
event Cloned(address indexed clone);
constructor(address _vault) public BaseStrategy(_vault) {
debtThreshold = 100 * 1e18;
}
function clone(address _vault) external returns (address newStrategy) {
newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender);
}
function clone(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _strategist, _rewards, _keeper);
emit Cloned(newStrategy);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) external virtual {
_initialize(_vault, _strategist, _rewards, _keeper);
}
function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized {
withdrawalThreshold = _threshold;
}
function setPriceOracle(address _oracle) external onlyAuthorized {
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiser";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr();
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav = nav.add(want.balanceOf(address(this)));
return nav;
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function estimatedAPR() public view returns (uint256) {
uint256 bal = estimatedTotalAssets();
if (bal == 0) {
return 0;
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
return weightedAPR.div(bal);
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR = weightedAPR.add(lenders[i].weightedApr());
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR = weightedAPR.add(lowestApr.mul(change));
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav = nav.add(lenders[i].nav());
}
return nav;
}
// we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
_debtOutstanding; //ignored. we handle it in prepare return
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if (lenders.length == 0) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000. 500 means 50% etc
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[i].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share = share.add(_newPositions[i].share);
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
if (lenders.length == 0) {
return 0;
}
//dont withdraw dust
if (_amount < withdrawalThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn));
j++;
//dont want infinite loop
if (j >= 6) {
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded, 0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded, 0);
} else {
return (received, 0);
}
}
}
function ethToWant(uint256 _amount) public override view returns (uint256) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256) {
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if (address(want) == weth) {
wantCallCost = callCost;
} else if (wantToEthOracle == address(0)) {
wantCallCost = ethToWant(callCost);
} else {
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//To calculate our potential profit increase we work out how much extra
//we would make in a typical harvest interlude. That is maxReportingDelay
//then we see if the extra profit is worth more than the gas cost * profitFactor
//safe math not needed here
//apr is scaled by 1e18 so we downscale here
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR);
uint256 wantCallCost = _callCostToWant(callCost);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
function liquidateAllPositions() internal override returns (uint256 _amountFreed) {
_amountFreed = _withdrawSome(lentTotalAssets());
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
(, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding);
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | /********************
*
* A lender optimisation strategy for any erc20 asset
* https://github.com/Grandthrax/yearnV2-generic-lender-strat
* v0.3.1
*
* This strategy works by taking plugins designed for standard lending platforms
* It automatically chooses the best yield generating platform and adjusts accordingly
* The adjustment is sub optimal so there is an additional option to manually set position
*
********************* */ | NatSpecMultiLine | prepareReturn | function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 total = looseAssets.add(lentAssets);
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
| // we need to free up profit plus _debtOutstanding.
// If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope... | LineComment | v0.6.12+commit.27d51765 | Unknown | ipfs://7a224399c14c11ec8e7f566fabefc939a638034f3ad5dd97286939b9860a8e5f | {
"func_code_index": [
10463,
13221
]
} | 2,399 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.