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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SkrumbleCandyToken
|
SkrumbleCandyToken.sol
|
0x55d260f12a6627a11aa10256f00cfacc48994aa8
|
Solidity
|
SkrumbleCandyToken
|
contract SkrumbleCandyToken is StandardToken {
string public name = "Skrumble Candy Token";
string public symbol = "SKM-CDY";
uint8 public decimals = 18;
/**
* @dev Constructor, takes intial Token.
*/
function SkrumbleCandyToken() public {
totalSupply_ = 3000000 * 1 ether;
balances[msg.sender] = totalSupply_;
}
/**
* @dev Batch transfer some tokens to some addresses, address and value is one-on-one.
* @param _dests Array of addresses
* @param _values Array of transfer tokens number
*/
function batchTransfer(address[] _dests, uint256[] _values) public {
require(_dests.length == _values.length);
uint256 i = 0;
while (i < _dests.length) {
transfer(_dests[i], _values[i]);
i += 1;
}
}
/**
* @dev Batch transfer equal tokens amout to some addresses
* @param _dests Array of addresses
* @param _value Number of transfer tokens amount
*/
function batchTransferSingleValue(address[] _dests, uint256 _value) public {
uint256 i = 0;
while (i < _dests.length) {
transfer(_dests[i], _value);
i += 1;
}
}
}
|
batchTransfer
|
function batchTransfer(address[] _dests, uint256[] _values) public {
require(_dests.length == _values.length);
uint256 i = 0;
while (i < _dests.length) {
transfer(_dests[i], _values[i]);
i += 1;
}
}
|
/**
* @dev Batch transfer some tokens to some addresses, address and value is one-on-one.
* @param _dests Array of addresses
* @param _values Array of transfer tokens number
*/
|
NatSpecMultiLine
|
v0.4.18+commit.9cf6e910
|
bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2
|
{
"func_code_index": [
590,
860
]
}
| 12,100
|
|||
SkrumbleCandyToken
|
SkrumbleCandyToken.sol
|
0x55d260f12a6627a11aa10256f00cfacc48994aa8
|
Solidity
|
SkrumbleCandyToken
|
contract SkrumbleCandyToken is StandardToken {
string public name = "Skrumble Candy Token";
string public symbol = "SKM-CDY";
uint8 public decimals = 18;
/**
* @dev Constructor, takes intial Token.
*/
function SkrumbleCandyToken() public {
totalSupply_ = 3000000 * 1 ether;
balances[msg.sender] = totalSupply_;
}
/**
* @dev Batch transfer some tokens to some addresses, address and value is one-on-one.
* @param _dests Array of addresses
* @param _values Array of transfer tokens number
*/
function batchTransfer(address[] _dests, uint256[] _values) public {
require(_dests.length == _values.length);
uint256 i = 0;
while (i < _dests.length) {
transfer(_dests[i], _values[i]);
i += 1;
}
}
/**
* @dev Batch transfer equal tokens amout to some addresses
* @param _dests Array of addresses
* @param _value Number of transfer tokens amount
*/
function batchTransferSingleValue(address[] _dests, uint256 _value) public {
uint256 i = 0;
while (i < _dests.length) {
transfer(_dests[i], _value);
i += 1;
}
}
}
|
batchTransferSingleValue
|
function batchTransferSingleValue(address[] _dests, uint256 _value) public {
uint256 i = 0;
while (i < _dests.length) {
transfer(_dests[i], _value);
i += 1;
}
}
|
/**
* @dev Batch transfer equal tokens amout to some addresses
* @param _dests Array of addresses
* @param _value Number of transfer tokens amount
*/
|
NatSpecMultiLine
|
v0.4.18+commit.9cf6e910
|
bzzr://24e639f9833c8209b754bbd6a3b1ce87b9803b9becd8fc0a75b1a7929adcc1d2
|
{
"func_code_index": [
1038,
1261
]
}
| 12,101
|
|||
SiaToken
|
SiaToken.sol
|
0x58ea375734e9a49a5abaafaa1cdcede99b375381
|
Solidity
|
SiaToken
|
contract SiaToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Sia";
name = "Sia Token";
decimals = 0;
_totalSupply = 20000;
balances[0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861] = _totalSupply;
emit Transfer(address(0), 0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
|
LineComment
|
totalSupply
|
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
|
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.25-nightly.2018.5.16+commit.3897c367
|
bzzr://7db7f405de907949fc83ee5532952db3be9c7c536a087ebc1dd98f4a4297fe86
|
{
"func_code_index": [
971,
1092
]
}
| 12,102
|
|
SiaToken
|
SiaToken.sol
|
0x58ea375734e9a49a5abaafaa1cdcede99b375381
|
Solidity
|
SiaToken
|
contract SiaToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Sia";
name = "Sia Token";
decimals = 0;
_totalSupply = 20000;
balances[0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861] = _totalSupply;
emit Transfer(address(0), 0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
|
LineComment
|
balanceOf
|
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
|
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.25-nightly.2018.5.16+commit.3897c367
|
bzzr://7db7f405de907949fc83ee5532952db3be9c7c536a087ebc1dd98f4a4297fe86
|
{
"func_code_index": [
1312,
1441
]
}
| 12,103
|
|
SiaToken
|
SiaToken.sol
|
0x58ea375734e9a49a5abaafaa1cdcede99b375381
|
Solidity
|
SiaToken
|
contract SiaToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Sia";
name = "Sia Token";
decimals = 0;
_totalSupply = 20000;
balances[0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861] = _totalSupply;
emit Transfer(address(0), 0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
|
LineComment
|
transfer
|
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
|
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.25-nightly.2018.5.16+commit.3897c367
|
bzzr://7db7f405de907949fc83ee5532952db3be9c7c536a087ebc1dd98f4a4297fe86
|
{
"func_code_index": [
1785,
2132
]
}
| 12,104
|
|
SiaToken
|
SiaToken.sol
|
0x58ea375734e9a49a5abaafaa1cdcede99b375381
|
Solidity
|
SiaToken
|
contract SiaToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Sia";
name = "Sia Token";
decimals = 0;
_totalSupply = 20000;
balances[0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861] = _totalSupply;
emit Transfer(address(0), 0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
|
LineComment
|
approve
|
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
|
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.25-nightly.2018.5.16+commit.3897c367
|
bzzr://7db7f405de907949fc83ee5532952db3be9c7c536a087ebc1dd98f4a4297fe86
|
{
"func_code_index": [
2640,
2853
]
}
| 12,105
|
|
SiaToken
|
SiaToken.sol
|
0x58ea375734e9a49a5abaafaa1cdcede99b375381
|
Solidity
|
SiaToken
|
contract SiaToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Sia";
name = "Sia Token";
decimals = 0;
_totalSupply = 20000;
balances[0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861] = _totalSupply;
emit Transfer(address(0), 0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
|
LineComment
|
transferFrom
|
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
|
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.25-nightly.2018.5.16+commit.3897c367
|
bzzr://7db7f405de907949fc83ee5532952db3be9c7c536a087ebc1dd98f4a4297fe86
|
{
"func_code_index": [
3384,
3747
]
}
| 12,106
|
|
SiaToken
|
SiaToken.sol
|
0x58ea375734e9a49a5abaafaa1cdcede99b375381
|
Solidity
|
SiaToken
|
contract SiaToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Sia";
name = "Sia Token";
decimals = 0;
_totalSupply = 20000;
balances[0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861] = _totalSupply;
emit Transfer(address(0), 0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
|
LineComment
|
allowance
|
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
|
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.25-nightly.2018.5.16+commit.3897c367
|
bzzr://7db7f405de907949fc83ee5532952db3be9c7c536a087ebc1dd98f4a4297fe86
|
{
"func_code_index": [
4030,
4186
]
}
| 12,107
|
|
SiaToken
|
SiaToken.sol
|
0x58ea375734e9a49a5abaafaa1cdcede99b375381
|
Solidity
|
SiaToken
|
contract SiaToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Sia";
name = "Sia Token";
decimals = 0;
_totalSupply = 20000;
balances[0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861] = _totalSupply;
emit Transfer(address(0), 0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
|
LineComment
|
approveAndCall
|
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
|
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.25-nightly.2018.5.16+commit.3897c367
|
bzzr://7db7f405de907949fc83ee5532952db3be9c7c536a087ebc1dd98f4a4297fe86
|
{
"func_code_index": [
4541,
4863
]
}
| 12,108
|
|
SiaToken
|
SiaToken.sol
|
0x58ea375734e9a49a5abaafaa1cdcede99b375381
|
Solidity
|
SiaToken
|
contract SiaToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Sia";
name = "Sia Token";
decimals = 0;
_totalSupply = 20000;
balances[0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861] = _totalSupply;
emit Transfer(address(0), 0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
|
LineComment
|
function () public payable {
revert();
}
|
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.25-nightly.2018.5.16+commit.3897c367
|
bzzr://7db7f405de907949fc83ee5532952db3be9c7c536a087ebc1dd98f4a4297fe86
|
{
"func_code_index": [
5055,
5114
]
}
| 12,109
|
||
SiaToken
|
SiaToken.sol
|
0x58ea375734e9a49a5abaafaa1cdcede99b375381
|
Solidity
|
SiaToken
|
contract SiaToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "Sia";
name = "Sia Token";
decimals = 0;
_totalSupply = 20000;
balances[0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861] = _totalSupply;
emit Transfer(address(0), 0x1CB2A100447408a0ACbDAde9B6d7824EB57e0861, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
emit TransferTokens(msg.sender, to, tokens, uint(now));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
|
LineComment
|
transferAnyERC20Token
|
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
|
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.25-nightly.2018.5.16+commit.3897c367
|
bzzr://7db7f405de907949fc83ee5532952db3be9c7c536a087ebc1dd98f4a4297fe86
|
{
"func_code_index": [
5347,
5536
]
}
| 12,110
|
|
Wearables
|
contracts/ERC1155Tradable.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155Tradable
|
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
|
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
|
NatSpecMultiLine
|
totalSupply
|
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
|
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
1463,
1576
]
}
| 12,111
|
Wearables
|
contracts/ERC1155Tradable.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155Tradable
|
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
|
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
|
NatSpecMultiLine
|
setBaseMetadataURI
|
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
|
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
1705,
1851
]
}
| 12,112
|
Wearables
|
contracts/ERC1155Tradable.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155Tradable
|
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
|
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
|
NatSpecMultiLine
|
create
|
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
|
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
2350,
2817
]
}
| 12,113
|
Wearables
|
contracts/ERC1155Tradable.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155Tradable
|
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
|
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
|
NatSpecMultiLine
|
mint
|
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
|
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
3117,
3330
]
}
| 12,114
|
Wearables
|
contracts/ERC1155Tradable.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155Tradable
|
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
|
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
|
NatSpecMultiLine
|
batchMint
|
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
|
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
3630,
4085
]
}
| 12,115
|
Wearables
|
contracts/ERC1155Tradable.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155Tradable
|
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
|
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
|
NatSpecMultiLine
|
isApprovedForAll
|
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
|
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
4206,
4610
]
}
| 12,116
|
Wearables
|
contracts/ERC1155Tradable.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155Tradable
|
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
|
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
|
NatSpecMultiLine
|
_exists
|
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
|
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
4835,
4954
]
}
| 12,117
|
Wearables
|
contracts/ERC1155Tradable.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155Tradable
|
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
|
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
|
NatSpecMultiLine
|
_getNextTokenID
|
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
|
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
5092,
5195
]
}
| 12,118
|
Wearables
|
contracts/ERC1155Tradable.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155Tradable
|
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balances[msg.sender][_id] > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) public {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
}
function uri(
uint256 _id
) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(
baseMetadataURI,
Strings.uint2str(_id)
);
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(
string memory _newBaseMetadataURI
) public onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] += _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(creators[_id] == msg.sender, "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED");
uint256 quantity = _quantities[i];
tokenSupply[_id] += quantity;
}
_batchMint(_to, _ids, _quantities, _data);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
|
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
|
NatSpecMultiLine
|
_incrementTokenTypeId
|
function _incrementTokenTypeId() private {
_currentTokenID++;
}
|
/**
* @dev increments the value of _currentTokenID
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
5265,
5340
]
}
| 12,119
|
HonestisNetworkTokenWire3
|
HonestisNetworkTokenWire3.sol
|
0x657c7739e165ad0b0a16ff6851f8587324b8a515
|
Solidity
|
StandardToken
|
contract StandardToken is ERC20, SafeMath {
/* Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
/* Actual balances of token holders */
mapping(address => uint) balances;
/* approve() allowances */
mapping (address => mapping (address => uint)) allowed;
/* Interface declaration */
function isToken() public constant returns (bool weAre) {
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
|
/**
* Standard ERC20 token with Short Hand Attack and approve() race condition mitigation.
*
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
|
NatSpecMultiLine
|
isToken
|
function isToken() public constant returns (bool weAre) {
return true;
}
|
/* Interface declaration */
|
Comment
|
v0.4.21+commit.dfe3193c
|
bzzr://c96505ef63b9df52f56b03b181822ec2dd0ad6439974941e1debdbfc01ba2ee3
|
{
"func_code_index": [
375,
458
]
}
| 12,120
|
|
HonestisNetworkTokenWire3
|
HonestisNetworkTokenWire3.sol
|
0x657c7739e165ad0b0a16ff6851f8587324b8a515
|
Solidity
|
HonestisNetworkTokenWire3
|
contract HonestisNetworkTokenWire3{
string public name = "Honestis.Network Token Version 1";
string public symbol = "HNT";
uint8 public constant decimals = 18; // 18 decimal places, the same as ETC/ETH/HEE.
// The funding cap in weis.
// was not reached about 93% was sold uint256 public constant tokenCreationCap = 66200 * 1000 * ether ;
// Receives ETH and its own H.N Token endowment.
address public honestisFort = 0xF03e8E4cbb2865fCc5a02B61cFCCf86E9aE021b5;
// NOT APPLY
address public migrationMaster = 0x0f32f4b37684be8a1ce1b2ed765d2d893fa1b419;
// The current total token supply.
//totalsupply
// uint256 public constant allchainstotalsupply =61172163.78335328 ether;
// uint256 public constant supply on chain 1st and 2nd =57872163.78335328 ether;
// uint256 public constant supply4chains34 = 3300000.0 ether;
uint256 public constant supply = 3300000.0 ether;
//61172163 783353280000000000
// was 61168800
//chains:
address public firstChainHNw1 = 0x0;
address public secondChainHNw2 = 0x0;
address public thirdChainETH = 0x0;
address public fourthChainETC = 0x0;
struct sendTokenAway{
StandardToken coinContract;
uint amount;
address recipient;
}
mapping(uint => sendTokenAway) transfers;
uint numTransfers=0;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
event UpdatedTokenInformation(string newName, string newSymbol);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function HonestisNetworkTokenWire3() {
// BALANCES
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// funcje transfer , fransfer from, allow, allowance , wywalic migrate i mastera , owner tylko do zmiany nazwy ??, total security check
//early adopters community 1
//balances[0xd57908dbe0e1353771db7f953E74a7936a5aAd70]= 61172163783353280000000000;
// 1st and 2nd chain balances[0xd57908dbe0e1353771db7f953E74a7936a5aAd70]=57872163783353280000000000;
// 3rd and 4th chain 3300000 000000000000000000; +3300000000000000000000000;
balances[0x8585d5a25b1fa2a0e6c3bcfc098195bac9789be2]=3300000000000000000000000;
}
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
//if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
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() payable {
}
function justSendDonations() external {
if (msg.sender != honestisFort) throw;
if (!honestisFort.send(this.balance)) throw;
}
function setTokenInformation(string _name, string _symbol) {
if (msg.sender != honestisFort) {
throw;
}
name = _name;
symbol = _symbol;
UpdatedTokenInformation(name, symbol);
}
function setChainsAddresses(address chainAd, int chainnumber) {
if (msg.sender != honestisFort) {
throw;
}
if(chainnumber==1){firstChainHNw1=chainAd;}
if(chainnumber==2){secondChainHNw2=chainAd;}
if(chainnumber==3){thirdChainETH=chainAd;}
if(chainnumber==4){fourthChainETC=chainAd;}
}
function HonestisnetworkICOregulations() external returns(string wow) {
return 'Regulations of preICO and ICO are present at website honestis.network and by using this smartcontract and blockchains you commit that you accept and will follow those rules';
}
// if accidentally other token was donated to Project Dev
function sendTokenAw(address StandardTokenAddress, address receiver, uint amount){
if (msg.sender != honestisFort) {
throw;
}
sendTokenAway t = transfers[numTransfers];
t.coinContract = StandardToken(StandardTokenAddress);
t.amount = amount;
t.recipient = receiver;
t.coinContract.transfer(receiver, amount);
numTransfers++;
}
}
|
// Honestis Network Token
|
LineComment
|
sendTokenAw
|
function sendTokenAw(address StandardTokenAddress, address receiver, uint amount){
if (msg.sender != honestisFort) {
throw;
}
sendTokenAway t = transfers[numTransfers];
t.coinContract = StandardToken(StandardTokenAddress);
t.amount = amount;
t.recipient = receiver;
t.coinContract.transfer(receiver, amount);
numTransfers++;
}
|
// if accidentally other token was donated to Project Dev
|
LineComment
|
v0.4.21+commit.dfe3193c
|
bzzr://c96505ef63b9df52f56b03b181822ec2dd0ad6439974941e1debdbfc01ba2ee3
|
{
"func_code_index": [
5154,
5511
]
}
| 12,121
|
|
LinearVesting
|
LinearVesting.sol
|
0x9bbd4b75f7cee00f446bb913a3ee2c981db0a8ab
|
Solidity
|
Ownable
|
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
|
/**
* @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() public {
owner = msg.sender;
}
|
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
|
NatSpecMultiLine
|
v0.4.18+commit.9cf6e910
|
bzzr://a5132317449768195cdbccedfb505371e253d5384662125a515927fe14f2d976
|
{
"func_code_index": [
253,
313
]
}
| 12,122
|
|
LinearVesting
|
LinearVesting.sol
|
0x9bbd4b75f7cee00f446bb913a3ee2c981db0a8ab
|
Solidity
|
Ownable
|
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
|
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
|
NatSpecMultiLine
|
transferOwnership
|
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
|
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
|
NatSpecMultiLine
|
v0.4.18+commit.9cf6e910
|
bzzr://a5132317449768195cdbccedfb505371e253d5384662125a515927fe14f2d976
|
{
"func_code_index": [
628,
804
]
}
| 12,123
|
|
LinearVesting
|
LinearVesting.sol
|
0x9bbd4b75f7cee00f446bb913a3ee2c981db0a8ab
|
Solidity
|
TokenVesting
|
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
|
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
|
NatSpecMultiLine
|
TokenVesting
|
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
|
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
|
NatSpecMultiLine
|
v0.4.18+commit.9cf6e910
|
bzzr://a5132317449768195cdbccedfb505371e253d5384662125a515927fe14f2d976
|
{
"func_code_index": [
996,
1344
]
}
| 12,124
|
|
LinearVesting
|
LinearVesting.sol
|
0x9bbd4b75f7cee00f446bb913a3ee2c981db0a8ab
|
Solidity
|
TokenVesting
|
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
|
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
|
NatSpecMultiLine
|
release
|
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
|
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
|
NatSpecMultiLine
|
v0.4.18+commit.9cf6e910
|
bzzr://a5132317449768195cdbccedfb505371e253d5384662125a515927fe14f2d976
|
{
"func_code_index": [
1466,
1731
]
}
| 12,125
|
|
LinearVesting
|
LinearVesting.sol
|
0x9bbd4b75f7cee00f446bb913a3ee2c981db0a8ab
|
Solidity
|
TokenVesting
|
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
|
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
|
NatSpecMultiLine
|
revoke
|
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
|
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
|
NatSpecMultiLine
|
v0.4.18+commit.9cf6e910
|
bzzr://a5132317449768195cdbccedfb505371e253d5384662125a515927fe14f2d976
|
{
"func_code_index": [
1941,
2285
]
}
| 12,126
|
|
LinearVesting
|
LinearVesting.sol
|
0x9bbd4b75f7cee00f446bb913a3ee2c981db0a8ab
|
Solidity
|
TokenVesting
|
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
|
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
|
NatSpecMultiLine
|
releasableAmount
|
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
|
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
|
NatSpecMultiLine
|
v0.4.18+commit.9cf6e910
|
bzzr://a5132317449768195cdbccedfb505371e253d5384662125a515927fe14f2d976
|
{
"func_code_index": [
2440,
2577
]
}
| 12,127
|
|
LinearVesting
|
LinearVesting.sol
|
0x9bbd4b75f7cee00f446bb913a3ee2c981db0a8ab
|
Solidity
|
TokenVesting
|
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
|
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
|
NatSpecMultiLine
|
vestedAmount
|
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
|
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
|
NatSpecMultiLine
|
v0.4.18+commit.9cf6e910
|
bzzr://a5132317449768195cdbccedfb505371e253d5384662125a515927fe14f2d976
|
{
"func_code_index": [
2703,
3116
]
}
| 12,128
|
|
Lister
|
Lister.sol
|
0x851e60609fd6e2d21038e43854cbd98470a8bafc
|
Solidity
|
TokenConfigInterface
|
interface TokenConfigInterface {
function admin() public returns(address);
function claimAdmin() public;
function transferAdminQuickly(address newAdmin) public;
// network
function listPairForReserve(address reserve, address src, address dest, bool add) public;
}
|
listPairForReserve
|
function listPairForReserve(address reserve, address src, address dest, bool add) public;
|
// network
|
LineComment
|
v0.4.18+commit.9cf6e910
|
bzzr://a9bbffdb53d38f5ed8ecd0f044957741dd8fc8593d424512b7abae0519be1285
|
{
"func_code_index": [
195,
289
]
}
| 12,129
|
|||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
allowance
|
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
|
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
3220,
3361
]
}
| 12,130
|
||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
approve
|
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
|
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
3834,
4259
]
}
| 12,131
|
||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
permit
|
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
|
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
4744,
5807
]
}
| 12,132
|
||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
balanceOf
|
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
|
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
6005,
6118
]
}
| 12,133
|
||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
transfer
|
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
|
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
6377,
6621
]
}
| 12,134
|
||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
transferFrom
|
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
|
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
6926,
7605
]
}
| 12,135
|
||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
delegate
|
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
|
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
7748,
7855
]
}
| 12,136
|
||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
delegateBySig
|
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
|
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
8284,
9081
]
}
| 12,137
|
||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
getCurrentVotes
|
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
|
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
9277,
9504
]
}
| 12,138
|
||
Comfi
|
Comfi.sol
|
0x752efadc0a7e05ad1bcccda22c141d01a75ef1e4
|
Solidity
|
Comfi
|
contract Comfi {
/// @notice EIP-20 token name for this token
string public constant name = "CompliFi";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMFI";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 10_000_000e18; // 10 millions Comfi
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comfi token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comfi::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::permit: invalid signature");
require(signatory == owner, "Comfi::permit: unauthorized");
require(now <= deadline, "Comfi::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comfi::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comfi::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comfi::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comfi::delegateBySig: invalid nonce");
require(now <= expiry, "Comfi::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comfi::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comfi::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comfi::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comfi::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comfi::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comfi::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comfi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
getPriorVotes
|
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comfi::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
|
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
|
NatSpecMultiLine
|
v0.5.17+commit.d19bba13
|
None
|
bzzr://10a2626788bdd54dd95ef89f52dc24783a50e4ee751dc9c4096a1880af2f38d0
|
{
"func_code_index": [
9930,
11154
]
}
| 12,139
|
||
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
isContract
|
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
|
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
1004,
1335
]
}
| 12,140
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
sendValue
|
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
|
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
2265,
2587
]
}
| 12,141
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionCall
|
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
|
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
3344,
3524
]
}
| 12,142
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionCall
|
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
|
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
3749,
3983
]
}
| 12,143
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionCallWithValue
|
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
|
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
4353,
4618
]
}
| 12,144
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionCallWithValue
|
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
|
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
4869,
5384
]
}
| 12,145
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionStaticCall
|
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
|
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
5564,
5768
]
}
| 12,146
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionStaticCall
|
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
|
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
5955,
6355
]
}
| 12,147
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionDelegateCall
|
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
|
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
6537,
6742
]
}
| 12,148
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionDelegateCall
|
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
|
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
6931,
7332
]
}
| 12,149
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
verifyCallResult
|
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
|
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
7555,
8272
]
}
| 12,150
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
SafeERC20
|
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
|
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
|
NatSpecMultiLine
|
safeApprove
|
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
|
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
791,
1412
]
}
| 12,151
|
QtokenBuy
|
QtokenBuy.sol
|
0xdadb1dba6df48852d103fa6499af1e3b87f4715c
|
Solidity
|
SafeERC20
|
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
|
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
|
NatSpecMultiLine
|
_callOptionalReturn
|
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
|
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
MIT
|
ipfs://4ea84d450607ec4c84b4d1071dcce7e6329fc172e64b4ec47c6014fa0aecc709
|
{
"func_code_index": [
2628,
3349
]
}
| 12,152
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
safeTransferFrom
|
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
|
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
1483,
2024
]
}
| 12,153
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
safeBatchTransferFrom
|
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
|
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
2414,
2921
]
}
| 12,154
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
_safeTransferFrom
|
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
|
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
3322,
3701
]
}
| 12,155
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
_callonERC1155Received
|
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
|
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
3811,
4243
]
}
| 12,156
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
_safeBatchTransferFrom
|
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
|
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
4546,
5236
]
}
| 12,157
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
_callonERC1155BatchReceived
|
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
|
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
5351,
5830
]
}
| 12,158
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
setApprovalForAll
|
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
|
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
6236,
6466
]
}
| 12,159
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
isApprovedForAll
|
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
|
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
6722,
6880
]
}
| 12,160
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
balanceOf
|
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
|
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
7230,
7360
]
}
| 12,161
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
balanceOfBatch
|
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
|
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
7645,
8148
]
}
| 12,162
|
Wearables
|
multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol
|
0xdb8cfaa3c4de5d03602a9da8d0ff248ff00fadef
|
Solidity
|
ERC1155
|
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount);
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
public
{
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeTransferFrom: INVALID_OPERATOR");
require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT");
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
{
// Requirements
require((msg.sender == _from) || operators[_from][msg.sender], "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR");
require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT");
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE");
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH");
// Number of transfer to execute
uint256 nTransfer = _ids.length;
// Executing all transfers
for (uint256 i = 0; i < nTransfer; i++) {
// Update storage balance of previous bin
balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE");
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view returns (uint256)
{
return balances[_owner][_id];
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view returns (uint256[] memory)
{
require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH");
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = balances[_owners[i]][_ids[i]];
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
}
|
/**
* @dev Implementation of Multi-Token Standard contract
*/
|
NatSpecMultiLine
|
supportsInterface
|
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
|
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
|
NatSpecMultiLine
|
v0.5.12+commit.7709ece9
|
None
|
bzzr://56974c90a9d406cedbf8e2c662434e6f24abd72fc449a93edc6c0776a34bafa4
|
{
"func_code_index": [
9205,
9448
]
}
| 12,163
|
MultisigVaultETH
|
openzeppelin-solidity/contracts/math/SafeMath.sol
|
0x97004c344d6061202d3e7ac59eddaeb5cd861ffd
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
|
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
|
NatSpecMultiLine
|
add
|
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
|
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
|
NatSpecMultiLine
|
v0.5.9+commit.e560f70d
|
{
"func_code_index": [
241,
421
]
}
| 12,164
|
||
MultisigVaultETH
|
openzeppelin-solidity/contracts/math/SafeMath.sol
|
0x97004c344d6061202d3e7ac59eddaeb5cd861ffd
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
|
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
|
NatSpecMultiLine
|
sub
|
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
|
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
|
NatSpecMultiLine
|
v0.5.9+commit.e560f70d
|
{
"func_code_index": [
681,
864
]
}
| 12,165
|
||
MultisigVaultETH
|
openzeppelin-solidity/contracts/math/SafeMath.sol
|
0x97004c344d6061202d3e7ac59eddaeb5cd861ffd
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
|
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
|
NatSpecMultiLine
|
mul
|
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
|
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
|
NatSpecMultiLine
|
v0.5.9+commit.e560f70d
|
{
"func_code_index": [
1100,
1562
]
}
| 12,166
|
||
MultisigVaultETH
|
openzeppelin-solidity/contracts/math/SafeMath.sol
|
0x97004c344d6061202d3e7ac59eddaeb5cd861ffd
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
|
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
|
NatSpecMultiLine
|
div
|
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
|
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
|
NatSpecMultiLine
|
v0.5.9+commit.e560f70d
|
{
"func_code_index": [
2013,
2343
]
}
| 12,167
|
||
MultisigVaultETH
|
openzeppelin-solidity/contracts/math/SafeMath.sol
|
0x97004c344d6061202d3e7ac59eddaeb5cd861ffd
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
|
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
|
NatSpecMultiLine
|
mod
|
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
|
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
|
NatSpecMultiLine
|
v0.5.9+commit.e560f70d
|
{
"func_code_index": [
2783,
2936
]
}
| 12,168
|
||
PIXELFROG
|
CryptoFrogFrens.sol
|
0x02f30927eb29f3f66031517bb3de3948f32ee019
|
Solidity
|
Base64
|
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
|
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <brecht@loopring.org>
|
NatSpecSingleLine
|
encode
|
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
|
/// @notice Encodes some bytes to the base64 representation
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
190,
1802
]
}
| 12,169
|
||
MultisigVaultETH
|
contracts/MultisigVaultETH.sol
|
0x97004c344d6061202d3e7ac59eddaeb5cd861ffd
|
Solidity
|
MultisigVaultETH
|
contract MultisigVaultETH {
using SafeMath for uint256;
struct Approval {
bool transfered;
uint256 coincieded;
mapping(address => bool) coinciedeParties;
}
uint256 private participantsAmount;
uint256 private signatureMinThreshold;
address payable private serviceAddress;
uint256 private serviceFeeMicro;
string private _symbol;
uint8 private _decimals;
address constant public ETHER_ADDRESS = address(0x1);
mapping(address => bool) public parties;
mapping(
// Destination
address => mapping(
// Amount
uint256 => Approval
)
) public approvals;
event ConfirmationReceived(address indexed from, address indexed destination, address currency, uint256 amount);
event ConsensusAchived(address indexed destination, address currency, uint256 amount);
/**
* @dev Construcor.
*
* Requirements:
* - `_signatureMinThreshold` .
* - `_parties`.
* - `_serviceAddress`.
* - `_serviceFeeMicro` represented by integer amount of million'th fractions.
*/
constructor(
uint256 _signatureMinThreshold,
address[] memory _parties,
address payable _serviceAddress,
uint256 _serviceFeeMicro
) public {
require(_parties.length > 0 && _parties.length <= 10);
require(_signatureMinThreshold > 0 && _signatureMinThreshold <= _parties.length);
signatureMinThreshold = _signatureMinThreshold;
serviceAddress = _serviceAddress;
serviceFeeMicro = _serviceFeeMicro;
_symbol = "ETH";
_decimals = 18;
for (uint256 i = 0; i < _parties.length; i++) parties[_parties[i]] = true;
}
modifier isMember() {
require(parties[msg.sender]);
_;
}
modifier sufficient(uint256 _amount) {
require(address(this).balance >= _amount);
_;
}
function partyCoincieded(
address _destination,
uint256 _amount,
address _partyAddress
) public view returns (bool) {
Approval storage approval = approvals[_destination][_amount];
return approval.coinciedeParties[_partyAddress];
}
// https://ethereum.stackexchange.com/questions/19341/address-send-vs-address-transfer-best-practice-usage
function approve(
address payable _destination,
uint256 _amount
) public isMember sufficient(_amount) returns (bool) {
Approval storage approval = approvals[_destination][_amount]; // Create new project
if (!approval.coinciedeParties[msg.sender]) {
approval.coinciedeParties[msg.sender] = true;
approval.coincieded += 1;
emit ConfirmationReceived(msg.sender, _destination, ETHER_ADDRESS, _amount);
if (
approval.coincieded >= signatureMinThreshold &&
!approval.transfered
) {
approval.transfered = true;
uint256 _amountToWithhold = _amount.mul(serviceFeeMicro).div(1000000);
uint256 _amountToRelease = _amount.sub(_amountToWithhold);
_destination.transfer(_amountToRelease); // Release funds
serviceAddress.transfer(_amountToWithhold); // Take service margin
emit ConsensusAchived(_destination, ETHER_ADDRESS, _amount);
}
return true;
} else {
// Raise will eat rest of gas. Lets not waist it. Just record this approval instead
return false;
}
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function() external payable { }
}
|
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
|
NatSpecMultiLine
|
approve
|
function approve(
address payable _destination,
uint256 _amount
) public isMember sufficient(_amount) returns (bool) {
Approval storage approval = approvals[_destination][_amount]; // Create new project
if (!approval.coinciedeParties[msg.sender]) {
approval.coinciedeParties[msg.sender] = true;
approval.coincieded += 1;
emit ConfirmationReceived(msg.sender, _destination, ETHER_ADDRESS, _amount);
if (
approval.coincieded >= signatureMinThreshold &&
!approval.transfered
) {
approval.transfered = true;
uint256 _amountToWithhold = _amount.mul(serviceFeeMicro).div(1000000);
uint256 _amountToRelease = _amount.sub(_amountToWithhold);
_destination.transfer(_amountToRelease); // Release funds
serviceAddress.transfer(_amountToWithhold); // Take service margin
emit ConsensusAchived(_destination, ETHER_ADDRESS, _amount);
}
return true;
} else {
// Raise will eat rest of gas. Lets not waist it. Just record this approval instead
return false;
}
}
|
// https://ethereum.stackexchange.com/questions/19341/address-send-vs-address-transfer-best-practice-usage
|
LineComment
|
v0.5.9+commit.e560f70d
|
{
"func_code_index": [
2339,
3591
]
}
| 12,170
|
||
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
startSale
|
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
|
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
1005,
1492
]
}
| 12,171
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
fund
|
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
|
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
1636,
1793
]
}
| 12,172
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
batchFund
|
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
|
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
1945,
2480
]
}
| 12,173
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
withdraw
|
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
|
// @notice Updates claimableTokens, sends all wei to the token holder
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
2558,
2966
]
}
| 12,174
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
batchWithdraw
|
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
|
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
3148,
3713
]
}
| 12,175
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
foundationWithdraw
|
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
|
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
3911,
4267
]
}
| 12,176
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
addContribution
|
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
|
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
4510,
5072
]
}
| 12,177
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
getTokensOwed
|
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
|
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
5184,
5546
]
}
| 12,178
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
getTotalTokensOwed
|
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
|
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
5736,
6098
]
}
| 12,179
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
getWeiContributed
|
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
|
// @notice returns the amount of wei contributed by _contributor on _day
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
6177,
6339
]
}
| 12,180
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
getTotalWeiContributed
|
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
|
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
6464,
6600
]
}
| 12,181
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
dayFor
|
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
|
// @notice return the day associated with this timestamp
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
6663,
6836
]
}
| 12,182
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
dayFinished
|
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
|
// @notice returns true if _day is finished
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
6886,
7095
]
}
| 12,183
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
duringSale
|
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
|
// @notice reverts if the current day isn't less than 365
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
7159,
7282
]
}
| 12,184
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
currentDay
|
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
|
// @notice return the current day
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
7324,
7418
]
}
| 12,185
|
|
TokenSale
|
contracts/TokenSale.sol
|
0xcca36039cfdd0753d3aa9f1b4bf35b606c8ed971
|
Solidity
|
TokenSale
|
contract TokenSale {
using SafeMath for *;
ERC20Interface mybToken;
struct Day {
uint totalWeiContributed;
mapping (address => uint) weiContributed;
}
// Constants
uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors
uint256 constant public tokensPerDay = 10**23; // 100,000 MYB
// MyBit addresses
address public owner;
address public mybitFoundation;
address public developmentFund;
uint256 public start; // The timestamp when sale starts
mapping (uint16 => Day) public day;
constructor(address _mybToken, address _mybFoundation, address _developmentFund)
public {
mybToken = ERC20Interface(_mybToken);
developmentFund = _developmentFund;
mybitFoundation = _mybFoundation;
owner = msg.sender;
}
// @notice owner can start the sale by transferring in required amount of MYB
// @dev the start time is used to determine which day the sale is on (day 0 = first day)
function startSale(uint _timestamp)
external
onlyOwner
returns (bool){
require(start == 0, 'Already started');
require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range');
uint saleAmount = tokensPerDay.mul(365);
require(mybToken.transferFrom(msg.sender, address(this), saleAmount));
start = _timestamp;
emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp);
return true;
}
// @notice contributor can contribute wei to sale on any current/future _day
// @dev only accepts contributions between days 0 - 364
function fund(uint16 _day)
payable
public
returns (bool) {
require(addContribution(msg.sender, msg.value, _day));
return true;
}
// @notice Send an index of days and your payment will be divided equally among them
// @dev WEI sent must divide equally into number of days.
function batchFund(uint16[] _day)
payable
external
returns (bool) {
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
require(msg.value >= _day.length); // need at least 1 wei per day
uint256 amountPerDay = msg.value.div(_day.length);
assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error
for (uint8 i = 0; i < _day.length; i++){
require(addContribution(msg.sender, amountPerDay, _day[i]));
}
return true;
}
// @notice Updates claimableTokens, sends all wei to the token holder
function withdraw(uint16 _day)
external
returns (bool) {
require(dayFinished(_day), "day has not finished funding");
Day storage thisDay = day[_day];
uint256 amount = getTokensOwed(msg.sender, _day);
delete thisDay.weiContributed[msg.sender];
mybToken.transfer(msg.sender, amount);
emit LogTokensCollected(msg.sender, amount, _day);
return true;
}
// @notice Updates claimableTokens, sends all tokens to contributor from previous days
// @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards
function batchWithdraw(uint16[] _day)
external
returns (bool) {
uint256 amount;
require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit
for (uint8 i = 0; i < _day.length; i++){
require(dayFinished(_day[i]));
uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]);
amount = amount.add(amountToAdd);
delete day[_day[i]].weiContributed[msg.sender];
emit LogTokensCollected(msg.sender, amountToAdd, _day[i]);
}
mybToken.transfer(msg.sender, amount);
return true;
}
// @notice owner can withdraw funds to the foundation wallet and ddf wallet
// @param (uint) _amount, The amount of wei to withdraw
// @dev must put in an _amount equally divisible by 2
function foundationWithdraw(uint _amount)
external
onlyOwner
returns (bool){
uint256 half = _amount.div(2);
assert (half.mul(2) == _amount); // check for rounding error
mybitFoundation.transfer(half);
developmentFund.transfer(half);
emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now));
return true;
}
// @notice updates ledger with the contribution from _investor
// @param (address) _investor: The sender of WEI to the contract
// @param (uint) _amount: The amount of WEI to add to _day
// @param (uint16) _day: The day to fund
function addContribution(address _investor, uint _amount, uint16 _day)
internal
returns (bool) {
require(_amount > 0, "must send ether with the call");
require(duringSale(_day), "day is not during the sale");
require(!dayFinished(_day), "day has already finished");
Day storage today = day[_day];
today.totalWeiContributed = today.totalWeiContributed.add(_amount);
today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount);
emit LogTokensPurchased(_investor, _amount, _day);
return true;
}
// @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay
function getTokensOwed(address _contributor, uint16 _day)
public
view
returns (uint256) {
require(dayFinished(_day));
Day storage thisDay = day[_day];
uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed);
return percentage.mul(tokensPerDay).div(scalingFactor);
}
// @notice gets the total amount of mybit owed to the contributor
// @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens.
function getTotalTokensOwed(address _contributor, uint16[] _days)
public
view
returns (uint256 amount) {
require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit
for (uint16 i = 0; i < _days.length; i++){
amount = amount.add(getTokensOwed(_contributor, _days[i]));
}
return amount;
}
// @notice returns the amount of wei contributed by _contributor on _day
function getWeiContributed(uint16 _day, address _contributor)
public
view
returns (uint256) {
return day[_day].weiContributed[_contributor];
}
// @notice returns amount of wei contributed on _day
// @dev if _day is outside of tokensale range it will return 0
function getTotalWeiContributed(uint16 _day)
public
view
returns (uint256) {
return day[_day].totalWeiContributed;
}
// @notice return the day associated with this timestamp
function dayFor(uint _timestamp)
public
view
returns (uint16) {
require(_timestamp >= start);
return uint16(_timestamp.sub(start).div(86400));
}
// @notice returns true if _day is finished
function dayFinished(uint16 _day)
public
view
returns (bool) {
if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished
return dayFor(now) > _day;
}
// @notice reverts if the current day isn't less than 365
function duringSale(uint16 _day)
public
view
returns (bool){
return start > 0 && _day <= uint16(364);
}
// @notice return the current day
function currentDay()
public
view
returns (uint16) {
return dayFor(now);
}
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
// @notice only owner address can call
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime);
event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day);
event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day);
event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day);
}
|
// @title MyBit Tokensale
// @notice A tokensale extending for 365 days. (0....364)
// @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day
// @notice Anyone can fund the current or future days with ETH
// @dev The current day is (timestamp - startTimestamp) / 24 hours
// @author Kyle Dewhurst, MyBit Foundation
|
LineComment
|
function ()
external
payable {
require(addContribution(msg.sender, msg.value, currentDay()));
}
|
// @notice Fallback function: Purchases contributor stake in the tokens for the current day
// @dev rejects contributions by means of the fallback function until timestamp > start
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
bzzr://f215848823315686a8490e24f02524a5f1cfb14494d6377095ade591033dabc4
|
{
"func_code_index": [
7607,
7721
]
}
| 12,186
|
||
Controller
|
contracts/interface/IPriceOracle.sol
|
0xd5b837a41a0d664ec28aa55b69b352944f741efa
|
Solidity
|
IPriceOracle
|
interface IPriceOracle {
/**
* @notice Get the underlying price of a iToken asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(address _iToken)
external
view
returns (uint256);
/**
* @notice Get the price of a underlying asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable and whether the price is valid.
*/
function getUnderlyingPriceAndStatus(address _iToken)
external
view
returns (uint256, bool);
}
|
getUnderlyingPrice
|
function getUnderlyingPrice(address _iToken)
external
view
returns (uint256);
|
/**
* @notice Get the underlying price of a iToken asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
|
NatSpecMultiLine
|
v0.6.12+commit.27d51765
|
{
"func_code_index": [
277,
382
]
}
| 12,187
|
||||
Controller
|
contracts/interface/IPriceOracle.sol
|
0xd5b837a41a0d664ec28aa55b69b352944f741efa
|
Solidity
|
IPriceOracle
|
interface IPriceOracle {
/**
* @notice Get the underlying price of a iToken asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(address _iToken)
external
view
returns (uint256);
/**
* @notice Get the price of a underlying asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable and whether the price is valid.
*/
function getUnderlyingPriceAndStatus(address _iToken)
external
view
returns (uint256, bool);
}
|
getUnderlyingPriceAndStatus
|
function getUnderlyingPriceAndStatus(address _iToken)
external
view
returns (uint256, bool);
|
/**
* @notice Get the price of a underlying asset
* @param _iToken The iToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable and whether the price is valid.
*/
|
NatSpecMultiLine
|
v0.6.12+commit.27d51765
|
{
"func_code_index": [
660,
780
]
}
| 12,188
|
||||
PERC20OnEosVault
|
contracts/PERC20OnEosVault.sol
|
0x70b2e4fc5793c3017d8e51e2c1987261cbceb0f3
|
Solidity
|
PERC20OnEosVault
|
contract PERC20OnEosVault is Withdrawable, IERC777Recipient {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
EnumerableSet.AddressSet private supportedTokens;
address public PNETWORK;
IWETH public weth;
event PegIn(address _tokenAddress, address _tokenSender, uint256 _tokenAmount, string _destinationAddress);
constructor(
address _weth,
address [] memory _tokensToSupport
) public {
PNETWORK = msg.sender;
for (uint256 i = 0; i < _tokensToSupport.length; i++) {
supportedTokens.add(_tokensToSupport[i]);
}
weth = IWETH(_weth);
_erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
modifier onlyPNetwork() {
require(msg.sender == PNETWORK, "Caller must be PNETWORK address!");
_;
}
receive() external payable {
require(msg.sender == address(weth));
}
function setWeth(address _weth) external onlyPNetwork {
weth = IWETH(_weth);
}
function setPNetwork(address _pnetwork) external onlyPNetwork {
PNETWORK = _pnetwork;
}
function IS_TOKEN_SUPPORTED(address _token) external view returns(bool) {
return supportedTokens.contains(_token);
}
function _owner() internal override returns(address) {
return PNETWORK;
}
function adminWithdrawAllowed(address asset) internal override view returns(uint) {
return supportedTokens.contains(asset) ? 0 : super.adminWithdrawAllowed(asset);
}
function addSupportedToken(
address _tokenAddress
)
external
onlyPNetwork
returns (bool SUCCESS)
{
supportedTokens.add(_tokenAddress);
return true;
}
function removeSupportedToken(
address _tokenAddress
)
external
onlyPNetwork
returns (bool SUCCESS)
{
return supportedTokens.remove(_tokenAddress);
}
function pegIn(
uint256 _tokenAmount,
address _tokenAddress,
string calldata _destinationAddress
)
external
returns (bool)
{
require(supportedTokens.contains(_tokenAddress), "Token at supplied address is NOT supported!");
require(_tokenAmount > 0, "Token amount must be greater than zero!");
IERC20(_tokenAddress).safeTransferFrom(msg.sender, address(this), _tokenAmount);
emit PegIn(_tokenAddress, msg.sender, _tokenAmount, _destinationAddress);
return true;
}
/**
* @dev Implementation of IERC777Recipient.
*/
function tokensReceived(
address /*operator*/,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata /*operatorData*/
) external override {
address _tokenAddress = msg.sender;
require(supportedTokens.contains(_tokenAddress), "caller is not a supported ERC777 token!");
require(to == address(this), "Token receiver is not this contract");
if (userData.length > 0) {
require(amount > 0, "Token amount must be greater than zero!");
(bytes32 tag, string memory _destinationAddress) = abi.decode(userData, (bytes32, string));
require(tag == keccak256("ERC777-pegIn"), "Invalid tag for automatic pegIn on ERC777 send");
emit PegIn(_tokenAddress, from, amount, _destinationAddress);
}
}
function pegInEth(string calldata _destinationAddress)
external
payable
returns (bool)
{
require(supportedTokens.contains(address(weth)), "WETH is NOT supported!");
require(msg.value > 0, "Ethers amount must be greater than zero!");
weth.deposit.value(msg.value)();
emit PegIn(address(weth), msg.sender, msg.value, _destinationAddress);
return true;
}
function pegOut(
address payable _tokenRecipient,
address _tokenAddress,
uint256 _tokenAmount
)
external
onlyPNetwork
returns (bool)
{
if (_tokenAddress == address(weth)) {
weth.withdraw(_tokenAmount);
_tokenRecipient.transfer(_tokenAmount);
} else {
IERC20(_tokenAddress).safeTransfer(_tokenRecipient, _tokenAmount);
}
return true;
}
function migrate(
address payable _to
)
external
onlyPNetwork
{
for (uint256 i = 0; i < supportedTokens.length(); i++) {
address tokenAddress = supportedTokens.at(i);
_migrateSingle(_to, tokenAddress);
}
}
function destroy()
external
onlyPNetwork
{
for (uint256 i = 0; i < supportedTokens.length(); i++) {
address tokenAddress = supportedTokens.at(i);
require(IERC20(tokenAddress).balanceOf(address(this)) == 0, "Balance of supported tokens must be 0");
}
selfdestruct(msg.sender);
}
function migrateSingle(
address payable _to,
address _tokenAddress
)
external
onlyPNetwork
{
_migrateSingle(_to, _tokenAddress);
}
function _migrateSingle(
address payable _to,
address _tokenAddress
)
private
{
if (supportedTokens.contains(_tokenAddress)) {
uint balance = IERC20(_tokenAddress).balanceOf(address(this));
IERC20(_tokenAddress).safeTransfer(_to, balance);
supportedTokens.remove(_tokenAddress);
}
}
}
|
tokensReceived
|
function tokensReceived(
address /*operator*/,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata /*operatorData*/
) external override {
address _tokenAddress = msg.sender;
require(supportedTokens.contains(_tokenAddress), "caller is not a supported ERC777 token!");
require(to == address(this), "Token receiver is not this contract");
if (userData.length > 0) {
require(amount > 0, "Token amount must be greater than zero!");
(bytes32 tag, string memory _destinationAddress) = abi.decode(userData, (bytes32, string));
require(tag == keccak256("ERC777-pegIn"), "Invalid tag for automatic pegIn on ERC777 send");
emit PegIn(_tokenAddress, from, amount, _destinationAddress);
}
}
|
/**
* @dev Implementation of IERC777Recipient.
*/
|
NatSpecMultiLine
|
v0.6.2+commit.bacdbe57
|
MIT
|
ipfs://5a15071870671d0041895477b6f56dd18edd2bc15cf9d53bb15492e46b274136
|
{
"func_code_index": [
2927,
3800
]
}
| 12,189
|
||
DistributeTokens
|
DistributeTokens.sol
|
0x1d3f069406e02936afaa0664bd81986d97858357
|
Solidity
|
Ownable
|
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
|
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
|
NatSpecMultiLine
|
transferOwnership
|
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
|
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
|
NatSpecMultiLine
|
v0.4.25+commit.59dbf8f1
|
MIT
|
bzzr://8051fbcc3ba7d32b1faf231d21a51d189e5b16607980a924486e27b59e7e55d0
|
{
"func_code_index": [
641,
822
]
}
| 12,190
|
DistributeTokens
|
DistributeTokens.sol
|
0x1d3f069406e02936afaa0664bd81986d97858357
|
Solidity
|
DistributeTokens
|
contract DistributeTokens is Ownable{
token tokenReward;
address public addressOfTokenUsedAsReward;
function setTokenReward(address _addr) public onlyOwner {
tokenReward = token(_addr);
addressOfTokenUsedAsReward = _addr;
}
function distributeVariable(address[] _addrs, uint[] _bals) public onlyOwner{
for(uint i = 0; i < _addrs.length; ++i){
tokenReward.transfer(_addrs[i],_bals[i]);
}
}
function distributeEth(address[] _addrs, uint[] _bals) public onlyOwner {
for(uint i = 0; i < _addrs.length; ++i) {
_addrs[i].transfer(_bals[i]);
}
}
function distributeFixed(address[] _addrs, uint _amoutToEach) public onlyOwner{
for(uint i = 0; i < _addrs.length; ++i){
tokenReward.transfer(_addrs[i],_amoutToEach);
}
}
// accept ETH
function () payable public {}
function withdrawTokens(uint _amount) public onlyOwner {
tokenReward.transfer(owner,_amount);
}
function withdrawEth(uint _value) public onlyOwner {
owner.transfer(_value);
}
}
|
function () payable public {}
|
// accept ETH
|
LineComment
|
v0.4.25+commit.59dbf8f1
|
MIT
|
bzzr://8051fbcc3ba7d32b1faf231d21a51d189e5b16607980a924486e27b59e7e55d0
|
{
"func_code_index": [
843,
875
]
}
| 12,191
|
|||
Kannabiz
|
Kannabiz.sol
|
0xd9506121d67fb918ac47af0b883730694be9377c
|
Solidity
|
ExtendedMath
|
library ExtendedMath
{
//return the smaller of the two inputs (a or b)
function limitLessThan(uint a, uint b) internal pure returns (uint c)
{
if(a > b) return b;
return a;
}
}
|
limitLessThan
|
function limitLessThan(uint a, uint b) internal pure returns (uint c)
{
if(a > b) return b;
return a;
}
|
//return the smaller of the two inputs (a or b)
|
LineComment
|
v0.4.18+commit.9cf6e910
|
MIT
|
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
|
{
"func_code_index": [
81,
217
]
}
| 12,192
|
||
Kannabiz
|
Kannabiz.sol
|
0xd9506121d67fb918ac47af0b883730694be9377c
|
Solidity
|
Kannabiz
|
contract Kannabiz is ERC20Interface, Owned
{
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount; //number of 'blocks' mined
uint public _BLOCKS_PER_READJUSTMENT = 4;
//a little number
uint public _MINIMUM_TARGET = 2**16;
//a big number is easier, just find a solution that is smaller
//uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping(address => bool) public frozenAccount; // Array of frozen accounts
mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts
mapping(uint256 => uint256) public eraVsMaxSupplyFactor;
event FrozenFunds(address target, bool frozen);
event whitelistedFunds(address target, bool whitelisted);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Kannabiz() public onlyOwner
{
symbol = "KK";
name = "Kannabiz Koin";
decimals = 8;
_totalSupply = 25000000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
eraVsMaxSupplyFactor[0] = 5;
eraVsMaxSupplyFactor[1] = 4;
eraVsMaxSupplyFactor[2] = 3;
eraVsMaxSupplyFactor[3] = 2;
eraVsMaxSupplyFactor[4] = 2;
eraVsMaxSupplyFactor[5] = 2;
eraVsMaxSupplyFactor[6] = 2;
eraVsMaxSupplyFactor[7] = 1;
eraVsMaxSupplyFactor[8] = 1;
eraVsMaxSupplyFactor[9] = 1;
eraVsMaxSupplyFactor[10] = 1;
eraVsMaxSupplyFactor[11] = 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success)
{
if (whitelistedAccount[msg.sender])
{
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
//Cannot mint more tokens than there are
assert(tokensMinted <= maxSupplyForEra);
assert(tokensMinted <= _totalSupply);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
else
{
return false;
}
}
//a new 'block' to be mined
function _startNewMiningEpoch() internal
{
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//4 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12)
{
rewardEra = rewardEra + 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
}
epochCount = epochCount.add(1);
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal
{
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 270 ethereum blocks per hour
//we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256
uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum
//if there were less eth blocks passed in time than expected
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 %
}
else
{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000
//make it easier
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET) //very difficult
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET) //very easy
{
miningTarget = _MAXIMUM_TARGET;
}
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32)
{
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint)
{
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint)
{
return miningTarget;
}
//10,000,000,000 coins total
//reward begins at 100,000 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint)
{
//once we get half way thru the coins, only get 50,000 per block
//every reward era, the reward amount halves.
return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ;
}
//help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if (challenge_digest == 9643712)
{
//suppress the warning
}
return digest;
}
//help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint)
{
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance)
{
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success)
{
// Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen
if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining)
{
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
}
function freezeAccount(address target, bool freeze) public onlyOwner
{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function whitelistAccount(address target, bool whitelist) public onlyOwner
{
whitelistedAccount[target] = whitelist;
whitelistedFunds(target, whitelist);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable
{
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
|
LineComment
|
Kannabiz
|
function Kannabiz() public onlyOwner
{
symbol = "KK";
name = "Kannabiz Koin";
decimals = 8;
_totalSupply = 25000000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
eraVsMaxSupplyFactor[0] = 5;
eraVsMaxSupplyFactor[1] = 4;
eraVsMaxSupplyFactor[2] = 3;
eraVsMaxSupplyFactor[3] = 2;
eraVsMaxSupplyFactor[4] = 2;
eraVsMaxSupplyFactor[5] = 2;
eraVsMaxSupplyFactor[6] = 2;
eraVsMaxSupplyFactor[7] = 1;
eraVsMaxSupplyFactor[8] = 1;
eraVsMaxSupplyFactor[9] = 1;
eraVsMaxSupplyFactor[10] = 1;
eraVsMaxSupplyFactor[11] = 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
_startNewMiningEpoch();
}
|
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
|
LineComment
|
v0.4.18+commit.9cf6e910
|
MIT
|
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
|
{
"func_code_index": [
1747,
2709
]
}
| 12,193
|
Kannabiz
|
Kannabiz.sol
|
0xd9506121d67fb918ac47af0b883730694be9377c
|
Solidity
|
Kannabiz
|
contract Kannabiz is ERC20Interface, Owned
{
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount; //number of 'blocks' mined
uint public _BLOCKS_PER_READJUSTMENT = 4;
//a little number
uint public _MINIMUM_TARGET = 2**16;
//a big number is easier, just find a solution that is smaller
//uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping(address => bool) public frozenAccount; // Array of frozen accounts
mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts
mapping(uint256 => uint256) public eraVsMaxSupplyFactor;
event FrozenFunds(address target, bool frozen);
event whitelistedFunds(address target, bool whitelisted);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Kannabiz() public onlyOwner
{
symbol = "KK";
name = "Kannabiz Koin";
decimals = 8;
_totalSupply = 25000000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
eraVsMaxSupplyFactor[0] = 5;
eraVsMaxSupplyFactor[1] = 4;
eraVsMaxSupplyFactor[2] = 3;
eraVsMaxSupplyFactor[3] = 2;
eraVsMaxSupplyFactor[4] = 2;
eraVsMaxSupplyFactor[5] = 2;
eraVsMaxSupplyFactor[6] = 2;
eraVsMaxSupplyFactor[7] = 1;
eraVsMaxSupplyFactor[8] = 1;
eraVsMaxSupplyFactor[9] = 1;
eraVsMaxSupplyFactor[10] = 1;
eraVsMaxSupplyFactor[11] = 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success)
{
if (whitelistedAccount[msg.sender])
{
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
//Cannot mint more tokens than there are
assert(tokensMinted <= maxSupplyForEra);
assert(tokensMinted <= _totalSupply);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
else
{
return false;
}
}
//a new 'block' to be mined
function _startNewMiningEpoch() internal
{
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//4 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12)
{
rewardEra = rewardEra + 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
}
epochCount = epochCount.add(1);
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal
{
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 270 ethereum blocks per hour
//we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256
uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum
//if there were less eth blocks passed in time than expected
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 %
}
else
{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000
//make it easier
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET) //very difficult
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET) //very easy
{
miningTarget = _MAXIMUM_TARGET;
}
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32)
{
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint)
{
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint)
{
return miningTarget;
}
//10,000,000,000 coins total
//reward begins at 100,000 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint)
{
//once we get half way thru the coins, only get 50,000 per block
//every reward era, the reward amount halves.
return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ;
}
//help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if (challenge_digest == 9643712)
{
//suppress the warning
}
return digest;
}
//help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint)
{
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance)
{
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success)
{
// Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen
if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining)
{
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
}
function freezeAccount(address target, bool freeze) public onlyOwner
{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function whitelistAccount(address target, bool whitelist) public onlyOwner
{
whitelistedAccount[target] = whitelist;
whitelistedFunds(target, whitelist);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable
{
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
|
LineComment
|
_startNewMiningEpoch
|
function _startNewMiningEpoch() internal
{
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//4 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12)
{
rewardEra = rewardEra + 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
}
epochCount = epochCount.add(1);
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
|
//a new 'block' to be mined
|
LineComment
|
v0.4.18+commit.9cf6e910
|
MIT
|
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
|
{
"func_code_index": [
4363,
5438
]
}
| 12,194
|
Kannabiz
|
Kannabiz.sol
|
0xd9506121d67fb918ac47af0b883730694be9377c
|
Solidity
|
Kannabiz
|
contract Kannabiz is ERC20Interface, Owned
{
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount; //number of 'blocks' mined
uint public _BLOCKS_PER_READJUSTMENT = 4;
//a little number
uint public _MINIMUM_TARGET = 2**16;
//a big number is easier, just find a solution that is smaller
//uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping(address => bool) public frozenAccount; // Array of frozen accounts
mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts
mapping(uint256 => uint256) public eraVsMaxSupplyFactor;
event FrozenFunds(address target, bool frozen);
event whitelistedFunds(address target, bool whitelisted);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Kannabiz() public onlyOwner
{
symbol = "KK";
name = "Kannabiz Koin";
decimals = 8;
_totalSupply = 25000000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
eraVsMaxSupplyFactor[0] = 5;
eraVsMaxSupplyFactor[1] = 4;
eraVsMaxSupplyFactor[2] = 3;
eraVsMaxSupplyFactor[3] = 2;
eraVsMaxSupplyFactor[4] = 2;
eraVsMaxSupplyFactor[5] = 2;
eraVsMaxSupplyFactor[6] = 2;
eraVsMaxSupplyFactor[7] = 1;
eraVsMaxSupplyFactor[8] = 1;
eraVsMaxSupplyFactor[9] = 1;
eraVsMaxSupplyFactor[10] = 1;
eraVsMaxSupplyFactor[11] = 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success)
{
if (whitelistedAccount[msg.sender])
{
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
//Cannot mint more tokens than there are
assert(tokensMinted <= maxSupplyForEra);
assert(tokensMinted <= _totalSupply);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
else
{
return false;
}
}
//a new 'block' to be mined
function _startNewMiningEpoch() internal
{
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//4 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12)
{
rewardEra = rewardEra + 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
}
epochCount = epochCount.add(1);
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal
{
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 270 ethereum blocks per hour
//we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256
uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum
//if there were less eth blocks passed in time than expected
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 %
}
else
{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000
//make it easier
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET) //very difficult
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET) //very easy
{
miningTarget = _MAXIMUM_TARGET;
}
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32)
{
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint)
{
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint)
{
return miningTarget;
}
//10,000,000,000 coins total
//reward begins at 100,000 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint)
{
//once we get half way thru the coins, only get 50,000 per block
//every reward era, the reward amount halves.
return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ;
}
//help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if (challenge_digest == 9643712)
{
//suppress the warning
}
return digest;
}
//help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint)
{
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance)
{
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success)
{
// Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen
if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining)
{
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
}
function freezeAccount(address target, bool freeze) public onlyOwner
{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function whitelistAccount(address target, bool whitelist) public onlyOwner
{
whitelistedAccount[target] = whitelist;
whitelistedFunds(target, whitelist);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable
{
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
|
LineComment
|
getChallengeNumber
|
function getChallengeNumber() public constant returns (bytes32)
{
return challengeNumber;
}
|
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
|
LineComment
|
v0.4.18+commit.9cf6e910
|
MIT
|
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
|
{
"func_code_index": [
7418,
7535
]
}
| 12,195
|
Kannabiz
|
Kannabiz.sol
|
0xd9506121d67fb918ac47af0b883730694be9377c
|
Solidity
|
Kannabiz
|
contract Kannabiz is ERC20Interface, Owned
{
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount; //number of 'blocks' mined
uint public _BLOCKS_PER_READJUSTMENT = 4;
//a little number
uint public _MINIMUM_TARGET = 2**16;
//a big number is easier, just find a solution that is smaller
//uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping(address => bool) public frozenAccount; // Array of frozen accounts
mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts
mapping(uint256 => uint256) public eraVsMaxSupplyFactor;
event FrozenFunds(address target, bool frozen);
event whitelistedFunds(address target, bool whitelisted);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Kannabiz() public onlyOwner
{
symbol = "KK";
name = "Kannabiz Koin";
decimals = 8;
_totalSupply = 25000000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
eraVsMaxSupplyFactor[0] = 5;
eraVsMaxSupplyFactor[1] = 4;
eraVsMaxSupplyFactor[2] = 3;
eraVsMaxSupplyFactor[3] = 2;
eraVsMaxSupplyFactor[4] = 2;
eraVsMaxSupplyFactor[5] = 2;
eraVsMaxSupplyFactor[6] = 2;
eraVsMaxSupplyFactor[7] = 1;
eraVsMaxSupplyFactor[8] = 1;
eraVsMaxSupplyFactor[9] = 1;
eraVsMaxSupplyFactor[10] = 1;
eraVsMaxSupplyFactor[11] = 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success)
{
if (whitelistedAccount[msg.sender])
{
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
//Cannot mint more tokens than there are
assert(tokensMinted <= maxSupplyForEra);
assert(tokensMinted <= _totalSupply);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
else
{
return false;
}
}
//a new 'block' to be mined
function _startNewMiningEpoch() internal
{
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//4 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12)
{
rewardEra = rewardEra + 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
}
epochCount = epochCount.add(1);
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal
{
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 270 ethereum blocks per hour
//we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256
uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum
//if there were less eth blocks passed in time than expected
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 %
}
else
{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000
//make it easier
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET) //very difficult
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET) //very easy
{
miningTarget = _MAXIMUM_TARGET;
}
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32)
{
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint)
{
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint)
{
return miningTarget;
}
//10,000,000,000 coins total
//reward begins at 100,000 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint)
{
//once we get half way thru the coins, only get 50,000 per block
//every reward era, the reward amount halves.
return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ;
}
//help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if (challenge_digest == 9643712)
{
//suppress the warning
}
return digest;
}
//help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint)
{
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance)
{
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success)
{
// Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen
if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining)
{
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
}
function freezeAccount(address target, bool freeze) public onlyOwner
{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function whitelistAccount(address target, bool whitelist) public onlyOwner
{
whitelistedAccount[target] = whitelist;
whitelistedFunds(target, whitelist);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable
{
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
|
LineComment
|
getMiningDifficulty
|
function getMiningDifficulty() public constant returns (uint)
{
return _MAXIMUM_TARGET.div(miningTarget);
}
|
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
|
LineComment
|
v0.4.18+commit.9cf6e910
|
MIT
|
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
|
{
"func_code_index": [
7620,
7753
]
}
| 12,196
|
Kannabiz
|
Kannabiz.sol
|
0xd9506121d67fb918ac47af0b883730694be9377c
|
Solidity
|
Kannabiz
|
contract Kannabiz is ERC20Interface, Owned
{
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount; //number of 'blocks' mined
uint public _BLOCKS_PER_READJUSTMENT = 4;
//a little number
uint public _MINIMUM_TARGET = 2**16;
//a big number is easier, just find a solution that is smaller
//uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping(address => bool) public frozenAccount; // Array of frozen accounts
mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts
mapping(uint256 => uint256) public eraVsMaxSupplyFactor;
event FrozenFunds(address target, bool frozen);
event whitelistedFunds(address target, bool whitelisted);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Kannabiz() public onlyOwner
{
symbol = "KK";
name = "Kannabiz Koin";
decimals = 8;
_totalSupply = 25000000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
eraVsMaxSupplyFactor[0] = 5;
eraVsMaxSupplyFactor[1] = 4;
eraVsMaxSupplyFactor[2] = 3;
eraVsMaxSupplyFactor[3] = 2;
eraVsMaxSupplyFactor[4] = 2;
eraVsMaxSupplyFactor[5] = 2;
eraVsMaxSupplyFactor[6] = 2;
eraVsMaxSupplyFactor[7] = 1;
eraVsMaxSupplyFactor[8] = 1;
eraVsMaxSupplyFactor[9] = 1;
eraVsMaxSupplyFactor[10] = 1;
eraVsMaxSupplyFactor[11] = 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success)
{
if (whitelistedAccount[msg.sender])
{
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
//Cannot mint more tokens than there are
assert(tokensMinted <= maxSupplyForEra);
assert(tokensMinted <= _totalSupply);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
else
{
return false;
}
}
//a new 'block' to be mined
function _startNewMiningEpoch() internal
{
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//4 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12)
{
rewardEra = rewardEra + 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
}
epochCount = epochCount.add(1);
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal
{
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 270 ethereum blocks per hour
//we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256
uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum
//if there were less eth blocks passed in time than expected
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 %
}
else
{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000
//make it easier
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET) //very difficult
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET) //very easy
{
miningTarget = _MAXIMUM_TARGET;
}
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32)
{
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint)
{
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint)
{
return miningTarget;
}
//10,000,000,000 coins total
//reward begins at 100,000 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint)
{
//once we get half way thru the coins, only get 50,000 per block
//every reward era, the reward amount halves.
return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ;
}
//help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if (challenge_digest == 9643712)
{
//suppress the warning
}
return digest;
}
//help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint)
{
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance)
{
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success)
{
// Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen
if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining)
{
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
}
function freezeAccount(address target, bool freeze) public onlyOwner
{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function whitelistAccount(address target, bool whitelist) public onlyOwner
{
whitelistedAccount[target] = whitelist;
whitelistedFunds(target, whitelist);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable
{
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
|
LineComment
|
getMiningReward
|
function getMiningReward() public constant returns (uint)
{
//once we get half way thru the coins, only get 50,000 per block
//every reward era, the reward amount halves.
return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ;
}
|
//10,000,000,000 coins total
//reward begins at 100,000 and is cut in half every reward era (as tokens are mined)
|
LineComment
|
v0.4.18+commit.9cf6e910
|
MIT
|
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
|
{
"func_code_index": [
7993,
8289
]
}
| 12,197
|
Kannabiz
|
Kannabiz.sol
|
0xd9506121d67fb918ac47af0b883730694be9377c
|
Solidity
|
Kannabiz
|
contract Kannabiz is ERC20Interface, Owned
{
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount; //number of 'blocks' mined
uint public _BLOCKS_PER_READJUSTMENT = 4;
//a little number
uint public _MINIMUM_TARGET = 2**16;
//a big number is easier, just find a solution that is smaller
//uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping(address => bool) public frozenAccount; // Array of frozen accounts
mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts
mapping(uint256 => uint256) public eraVsMaxSupplyFactor;
event FrozenFunds(address target, bool frozen);
event whitelistedFunds(address target, bool whitelisted);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Kannabiz() public onlyOwner
{
symbol = "KK";
name = "Kannabiz Koin";
decimals = 8;
_totalSupply = 25000000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
eraVsMaxSupplyFactor[0] = 5;
eraVsMaxSupplyFactor[1] = 4;
eraVsMaxSupplyFactor[2] = 3;
eraVsMaxSupplyFactor[3] = 2;
eraVsMaxSupplyFactor[4] = 2;
eraVsMaxSupplyFactor[5] = 2;
eraVsMaxSupplyFactor[6] = 2;
eraVsMaxSupplyFactor[7] = 1;
eraVsMaxSupplyFactor[8] = 1;
eraVsMaxSupplyFactor[9] = 1;
eraVsMaxSupplyFactor[10] = 1;
eraVsMaxSupplyFactor[11] = 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success)
{
if (whitelistedAccount[msg.sender])
{
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
//Cannot mint more tokens than there are
assert(tokensMinted <= maxSupplyForEra);
assert(tokensMinted <= _totalSupply);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
else
{
return false;
}
}
//a new 'block' to be mined
function _startNewMiningEpoch() internal
{
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//4 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12)
{
rewardEra = rewardEra + 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
}
epochCount = epochCount.add(1);
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal
{
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 270 ethereum blocks per hour
//we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256
uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum
//if there were less eth blocks passed in time than expected
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 %
}
else
{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000
//make it easier
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET) //very difficult
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET) //very easy
{
miningTarget = _MAXIMUM_TARGET;
}
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32)
{
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint)
{
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint)
{
return miningTarget;
}
//10,000,000,000 coins total
//reward begins at 100,000 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint)
{
//once we get half way thru the coins, only get 50,000 per block
//every reward era, the reward amount halves.
return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ;
}
//help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if (challenge_digest == 9643712)
{
//suppress the warning
}
return digest;
}
//help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint)
{
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance)
{
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success)
{
// Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen
if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining)
{
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
}
function freezeAccount(address target, bool freeze) public onlyOwner
{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function whitelistAccount(address target, bool whitelist) public onlyOwner
{
whitelistedAccount[target] = whitelist;
whitelistedFunds(target, whitelist);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable
{
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
|
LineComment
|
getMintDigest
|
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if (challenge_digest == 9643712)
{
//suppress the warning
}
return digest;
}
|
//help debug mining software
|
LineComment
|
v0.4.18+commit.9cf6e910
|
MIT
|
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
|
{
"func_code_index": [
8325,
8672
]
}
| 12,198
|
Kannabiz
|
Kannabiz.sol
|
0xd9506121d67fb918ac47af0b883730694be9377c
|
Solidity
|
Kannabiz
|
contract Kannabiz is ERC20Interface, Owned
{
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount; //number of 'blocks' mined
uint public _BLOCKS_PER_READJUSTMENT = 4;
//a little number
uint public _MINIMUM_TARGET = 2**16;
//a big number is easier, just find a solution that is smaller
//uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping(address => bool) public frozenAccount; // Array of frozen accounts
mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts
mapping(uint256 => uint256) public eraVsMaxSupplyFactor;
event FrozenFunds(address target, bool frozen);
event whitelistedFunds(address target, bool whitelisted);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function Kannabiz() public onlyOwner
{
symbol = "KK";
name = "Kannabiz Koin";
decimals = 8;
_totalSupply = 25000000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
eraVsMaxSupplyFactor[0] = 5;
eraVsMaxSupplyFactor[1] = 4;
eraVsMaxSupplyFactor[2] = 3;
eraVsMaxSupplyFactor[3] = 2;
eraVsMaxSupplyFactor[4] = 2;
eraVsMaxSupplyFactor[5] = 2;
eraVsMaxSupplyFactor[6] = 2;
eraVsMaxSupplyFactor[7] = 1;
eraVsMaxSupplyFactor[8] = 1;
eraVsMaxSupplyFactor[9] = 1;
eraVsMaxSupplyFactor[10] = 1;
eraVsMaxSupplyFactor[11] = 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success)
{
if (whitelistedAccount[msg.sender])
{
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
//Cannot mint more tokens than there are
assert(tokensMinted <= maxSupplyForEra);
assert(tokensMinted <= _totalSupply);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
else
{
return false;
}
}
//a new 'block' to be mined
function _startNewMiningEpoch() internal
{
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//4 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12)
{
rewardEra = rewardEra + 1;
maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals);
}
epochCount = epochCount.add(1);
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal
{
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 270 ethereum blocks per hour
//we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256
uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum
//if there were less eth blocks passed in time than expected
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 %
}
else
{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000
//make it easier
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET) //very difficult
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET) //very easy
{
miningTarget = _MAXIMUM_TARGET;
}
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32)
{
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint)
{
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint)
{
return miningTarget;
}
//10,000,000,000 coins total
//reward begins at 100,000 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint)
{
//once we get half way thru the coins, only get 50,000 per block
//every reward era, the reward amount halves.
return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ;
}
//help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if (challenge_digest == 9643712)
{
//suppress the warning
}
return digest;
}
//help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint)
{
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance)
{
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success)
{
// Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen
if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to]))
{
return false;
}
else
{
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining)
{
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
{
if ((frozenAccount[msg.sender]) || (frozenAccount[spender]))
{
return false;
}
else
{
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
}
function freezeAccount(address target, bool freeze) public onlyOwner
{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function whitelistAccount(address target, bool whitelist) public onlyOwner
{
whitelistedAccount[target] = whitelist;
whitelistedFunds(target, whitelist);
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable
{
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
|
LineComment
|
checkMintSolution
|
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success)
{
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
|
//help debug mining software
|
LineComment
|
v0.4.18+commit.9cf6e910
|
MIT
|
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
|
{
"func_code_index": [
8708,
9040
]
}
| 12,199
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.