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
PrimeDeployable
_Voting.sol
0xdefac16715671b7b6aeefe012125f1e19ee4b7d7
Solidity
Voting
contract Voting { using SafeMath for uint256; struct Suggestion { uint256 votes; bool created; address creator; string text; } // This stores how many votes a user has cast on a suggestion mapping(uint256 => mapping(address => uint256)) private voted; // This map stores the suggestions, and they're retrieved using their ID number mapping(uint256 => Suggestion) internal suggestions; // This keeps track of the number of suggestions in the system uint256 public suggestionCount; // If true, a wallet can only vote on a suggestion once bool public oneVotePerAccount = true; event SuggestionCreated(uint256 suggestionId, string text); event Votes( address voter, uint256 indexed suggestionId, uint256 votes, uint256 totalVotes, string comment ); /** * @dev Gets the number of votes a suggestion has received. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getVotes(uint256 suggestionId) public view returns (uint256) { return suggestions[suggestionId].votes; } /** * @dev Gets the number of votes for every suggestion in the contract. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getAllVotes() public view returns (uint256[] memory) { uint256[] memory votes = new uint256[](suggestionCount); for (uint256 i = 0; i < suggestionCount; i++) { votes[i] = suggestions[i].votes; } return votes; } /** * @dev Gets the text of a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getSuggestionText(uint256 suggestionId) public view returns (string memory) { return suggestions[suggestionId].text; } /** * @dev Gets whether or not an account has voted for a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function hasVoted(address account, uint256 suggestionId) public view returns (bool) { return voted[suggestionId][account] > 0; } /** * @dev Gets the number of votes an account has cast towards a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getAccountVotes(address account, uint256 suggestionId) public view returns (uint256) { return voted[suggestionId][account]; } /** * @dev Gets the creator of a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getSuggestionCreator(uint256 suggestionId) public view returns (address) { return suggestions[suggestionId].creator; } /** * @dev Gets the creator for every suggestion in the contract. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getAllSuggestionCreators() public view returns (address[] memory) { address[] memory creators = new address[](suggestionCount); for (uint256 i = 0; i < suggestionCount; i++) { creators[i] = suggestions[i].creator; } return creators; } /** * @dev Internal logic for creating a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function _createSuggestion(string memory text) internal { // The ID is just based on the suggestion count, so the IDs go 0, 1, 2, etc. uint256 suggestionId = suggestionCount++; // Starts at 0 votes suggestions[suggestionId] = Suggestion(0, true, msg.sender, text); emit SuggestionCreated(suggestionId, text); } /** * @dev Internal logic for voting. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function _vote( address account, uint256 suggestionId, uint256 votes, string memory comment ) internal returns (uint256) { if (oneVotePerAccount) { require(!hasVoted(account, suggestionId)); require(votes == 1); } Suggestion storage sugg = suggestions[suggestionId]; require(sugg.created); voted[suggestionId][account] = voted[suggestionId][account].add(votes); sugg.votes = sugg.votes.add(votes); emit Votes(account, suggestionId, votes, sugg.votes, comment); return sugg.votes; } }
/** * @dev Suggestions and Voting for token-holders. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */
NatSpecMultiLine
getAllSuggestionCreators
function getAllSuggestionCreators() public view returns (address[] memory) { address[] memory creators = new address[](suggestionCount); for (uint256 i = 0; i < suggestionCount; i++) { creators[i] = suggestions[i].creator; } return creators; }
/** * @dev Gets the creator for every suggestion in the contract. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://234bdf13169b58325b2dd630f037b819b4b9e91ab17cbe2e75dfde6bda4e82f6
{ "func_code_index": [ 3103, 3400 ] }
54,261
PrimeDeployable
_Voting.sol
0xdefac16715671b7b6aeefe012125f1e19ee4b7d7
Solidity
Voting
contract Voting { using SafeMath for uint256; struct Suggestion { uint256 votes; bool created; address creator; string text; } // This stores how many votes a user has cast on a suggestion mapping(uint256 => mapping(address => uint256)) private voted; // This map stores the suggestions, and they're retrieved using their ID number mapping(uint256 => Suggestion) internal suggestions; // This keeps track of the number of suggestions in the system uint256 public suggestionCount; // If true, a wallet can only vote on a suggestion once bool public oneVotePerAccount = true; event SuggestionCreated(uint256 suggestionId, string text); event Votes( address voter, uint256 indexed suggestionId, uint256 votes, uint256 totalVotes, string comment ); /** * @dev Gets the number of votes a suggestion has received. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getVotes(uint256 suggestionId) public view returns (uint256) { return suggestions[suggestionId].votes; } /** * @dev Gets the number of votes for every suggestion in the contract. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getAllVotes() public view returns (uint256[] memory) { uint256[] memory votes = new uint256[](suggestionCount); for (uint256 i = 0; i < suggestionCount; i++) { votes[i] = suggestions[i].votes; } return votes; } /** * @dev Gets the text of a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getSuggestionText(uint256 suggestionId) public view returns (string memory) { return suggestions[suggestionId].text; } /** * @dev Gets whether or not an account has voted for a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function hasVoted(address account, uint256 suggestionId) public view returns (bool) { return voted[suggestionId][account] > 0; } /** * @dev Gets the number of votes an account has cast towards a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getAccountVotes(address account, uint256 suggestionId) public view returns (uint256) { return voted[suggestionId][account]; } /** * @dev Gets the creator of a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getSuggestionCreator(uint256 suggestionId) public view returns (address) { return suggestions[suggestionId].creator; } /** * @dev Gets the creator for every suggestion in the contract. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getAllSuggestionCreators() public view returns (address[] memory) { address[] memory creators = new address[](suggestionCount); for (uint256 i = 0; i < suggestionCount; i++) { creators[i] = suggestions[i].creator; } return creators; } /** * @dev Internal logic for creating a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function _createSuggestion(string memory text) internal { // The ID is just based on the suggestion count, so the IDs go 0, 1, 2, etc. uint256 suggestionId = suggestionCount++; // Starts at 0 votes suggestions[suggestionId] = Suggestion(0, true, msg.sender, text); emit SuggestionCreated(suggestionId, text); } /** * @dev Internal logic for voting. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function _vote( address account, uint256 suggestionId, uint256 votes, string memory comment ) internal returns (uint256) { if (oneVotePerAccount) { require(!hasVoted(account, suggestionId)); require(votes == 1); } Suggestion storage sugg = suggestions[suggestionId]; require(sugg.created); voted[suggestionId][account] = voted[suggestionId][account].add(votes); sugg.votes = sugg.votes.add(votes); emit Votes(account, suggestionId, votes, sugg.votes, comment); return sugg.votes; } }
/** * @dev Suggestions and Voting for token-holders. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */
NatSpecMultiLine
_createSuggestion
function _createSuggestion(string memory text) internal { // The ID is just based on the suggestion count, so the IDs go 0, 1, 2, etc. uint256 suggestionId = suggestionCount++; // Starts at 0 votes suggestions[suggestionId] = Suggestion(0, true, msg.sender, text); emit SuggestionCreated(suggestionId, text); }
/** * @dev Internal logic for creating a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://234bdf13169b58325b2dd630f037b819b4b9e91ab17cbe2e75dfde6bda4e82f6
{ "func_code_index": [ 3568, 3928 ] }
54,262
PrimeDeployable
_Voting.sol
0xdefac16715671b7b6aeefe012125f1e19ee4b7d7
Solidity
Voting
contract Voting { using SafeMath for uint256; struct Suggestion { uint256 votes; bool created; address creator; string text; } // This stores how many votes a user has cast on a suggestion mapping(uint256 => mapping(address => uint256)) private voted; // This map stores the suggestions, and they're retrieved using their ID number mapping(uint256 => Suggestion) internal suggestions; // This keeps track of the number of suggestions in the system uint256 public suggestionCount; // If true, a wallet can only vote on a suggestion once bool public oneVotePerAccount = true; event SuggestionCreated(uint256 suggestionId, string text); event Votes( address voter, uint256 indexed suggestionId, uint256 votes, uint256 totalVotes, string comment ); /** * @dev Gets the number of votes a suggestion has received. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getVotes(uint256 suggestionId) public view returns (uint256) { return suggestions[suggestionId].votes; } /** * @dev Gets the number of votes for every suggestion in the contract. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getAllVotes() public view returns (uint256[] memory) { uint256[] memory votes = new uint256[](suggestionCount); for (uint256 i = 0; i < suggestionCount; i++) { votes[i] = suggestions[i].votes; } return votes; } /** * @dev Gets the text of a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getSuggestionText(uint256 suggestionId) public view returns (string memory) { return suggestions[suggestionId].text; } /** * @dev Gets whether or not an account has voted for a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function hasVoted(address account, uint256 suggestionId) public view returns (bool) { return voted[suggestionId][account] > 0; } /** * @dev Gets the number of votes an account has cast towards a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getAccountVotes(address account, uint256 suggestionId) public view returns (uint256) { return voted[suggestionId][account]; } /** * @dev Gets the creator of a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getSuggestionCreator(uint256 suggestionId) public view returns (address) { return suggestions[suggestionId].creator; } /** * @dev Gets the creator for every suggestion in the contract. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function getAllSuggestionCreators() public view returns (address[] memory) { address[] memory creators = new address[](suggestionCount); for (uint256 i = 0; i < suggestionCount; i++) { creators[i] = suggestions[i].creator; } return creators; } /** * @dev Internal logic for creating a suggestion. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function _createSuggestion(string memory text) internal { // The ID is just based on the suggestion count, so the IDs go 0, 1, 2, etc. uint256 suggestionId = suggestionCount++; // Starts at 0 votes suggestions[suggestionId] = Suggestion(0, true, msg.sender, text); emit SuggestionCreated(suggestionId, text); } /** * @dev Internal logic for voting. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */ function _vote( address account, uint256 suggestionId, uint256 votes, string memory comment ) internal returns (uint256) { if (oneVotePerAccount) { require(!hasVoted(account, suggestionId)); require(votes == 1); } Suggestion storage sugg = suggestions[suggestionId]; require(sugg.created); voted[suggestionId][account] = voted[suggestionId][account].add(votes); sugg.votes = sugg.votes.add(votes); emit Votes(account, suggestionId, votes, sugg.votes, comment); return sugg.votes; } }
/** * @dev Suggestions and Voting for token-holders. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */
NatSpecMultiLine
_vote
function _vote( address account, uint256 suggestionId, uint256 votes, string memory comment ) internal returns (uint256) { if (oneVotePerAccount) { require(!hasVoted(account, suggestionId)); require(votes == 1); } Suggestion storage sugg = suggestions[suggestionId]; require(sugg.created); voted[suggestionId][account] = voted[suggestionId][account].add(votes); sugg.votes = sugg.votes.add(votes); emit Votes(account, suggestionId, votes, sugg.votes, comment); return sugg.votes; }
/** * @dev Internal logic for voting. * * Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://234bdf13169b58325b2dd630f037b819b4b9e91ab17cbe2e75dfde6bda4e82f6
{ "func_code_index": [ 4081, 4697 ] }
54,263
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); }
/** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 815, 932 ] }
54,264
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1097, 1205 ] }
54,265
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
_transferOwnership
function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; }
/** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1343, 1521 ] }
54,266
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
mul
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = _a * _b; assert(c / _a == _b); return c; }
/** * @dev Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 89, 483 ] }
54,267
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
div
function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 567, 858 ] }
54,268
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
sub
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; }
/** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 972, 1094 ] }
54,269
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting '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; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
add
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1158, 1293 ] }
54,270
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
name
function name() public constant returns (string) { return mName; }
/// @return the name of the token
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1378, 1449 ] }
54,271
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
symbol
function symbol() public constant returns (string) { return mSymbol; }
/// @return the symbol of the token
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1493, 1568 ] }
54,272
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
granularity
function granularity() public constant returns (uint256) { return mGranularity; }
/// @return the granularity of the token
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1617, 1703 ] }
54,273
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
totalSupply
function totalSupply() public constant returns (uint256) { return mTotalSupply; }
/// @return the total supply of the token
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1753, 1839 ] }
54,274
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
balanceOf
function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; }
/// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 2022, 2137 ] }
54,275
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
defaultOperators
function defaultOperators() public view returns (address[]) { return mDefaultOperators; }
/// @notice Return the list of default operators /// @return the list of all the default operators
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 2249, 2343 ] }
54,276
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
send
function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); }
/// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 2547, 2704 ] }
54,277
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
authorizeOperator
function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); }
/// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 2867, 3228 ] }
54,278
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
revokeOperator
function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); }
/// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 3394, 3749 ] }
54,279
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
isOperatorFor
function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); }
/// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder`
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 4101, 4408 ] }
54,280
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
operatorSend
function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); }
/// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 4845, 5104 ] }
54,281
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
requireMultiple
function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); }
/// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 5704, 5847 ] }
54,282
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
isRegularAddress
function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; }
/// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract)
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 6063, 6331 ] }
54,283
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
doSend
function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); }
/// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 7141, 7949 ] }
54,284
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
doBurn
function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); }
/// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 8338, 8872 ] }
54,285
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
callRecipient
function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } }
/// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 9770, 10403 ] }
54,286
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777BaseToken
contract ERC777BaseToken is ERC777Token, ERC820Implementer { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; mapping(address => mapping(address => bool)) internal mAuthorized; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor(string _name, string _symbol, uint256 _granularity, address[] _defaultOperators) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", this); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public constant returns (string) { return mName; } /// @return the symbol of the token function symbol() public constant returns (string) { return mSymbol; } /// @return the granularity of the token function granularity() public constant returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public constant returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public constant returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[]) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, msg.sender, _to, _amount, _userData, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorized[_operator][msg.sender] = true; } AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) public { require(_operator != msg.sender); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorized[_operator][msg.sender] = false; } RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public constant returns (bool) { return (_operator == _tokenHolder || mAuthorized[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(msg.sender, _from, _to, _amount, _userData, _operatorData, true); } function burn(uint256 _amount, bytes _holderData) public { doBurn(msg.sender, msg.sender, _amount, _holderData, ""); } function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _tokenHolder)); doBurn(msg.sender, _tokenHolder, _amount, _holderData, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal constant returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `erc777_tokenHolder`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); Sent(_operator, _from, _to, _amount, _userData, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _holderData Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); callSender(_operator, _tokenHolder, 0x0, _amount, _holderData, _operatorData); Burned(_operator, _tokenHolder, _amount, _holderData, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); } }
/** * @title ERC777BaseToken */
NatSpecMultiLine
callSender
function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == 0) { return; } ERC777TokensSender(senderImplementation).tokensToSend(_operator, _from, _to, _amount, _userData, _operatorData); }
/// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _userData Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 11113, 11590 ] }
54,287
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777ERC20BaseToken
contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken { bool internal mErc20compatible; mapping(address => mapping(address => bool)) internal mAuthorized; mapping(address => mapping(address => uint256)) internal mAllowed; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible); _; } /// @notice For Backwards compatibility /// @return The decimls of the token. Forced to 18 in ERC777. function decimals() public erc20 constant returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) { return mAllowed[_owner][_spender]; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); if (mErc20compatible) { Transfer(_from, _to, _amount); } } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); if (mErc20compatible) { Transfer(_tokenHolder, 0x0, _amount); } } }
/** * @title ERC777ERC20BaseToken */
NatSpecMultiLine
decimals
function decimals() public erc20 constant returns (uint8) { return uint8(18); }
/// @notice For Backwards compatibility /// @return The decimls of the token. Forced to 18 in ERC777.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 992, 1076 ] }
54,288
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777ERC20BaseToken
contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken { bool internal mErc20compatible; mapping(address => mapping(address => bool)) internal mAuthorized; mapping(address => mapping(address => uint256)) internal mAllowed; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible); _; } /// @notice For Backwards compatibility /// @return The decimls of the token. Forced to 18 in ERC777. function decimals() public erc20 constant returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) { return mAllowed[_owner][_spender]; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); if (mErc20compatible) { Transfer(_from, _to, _amount); } } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); if (mErc20compatible) { Transfer(_tokenHolder, 0x0, _amount); } } }
/** * @title ERC777ERC20BaseToken */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; }
/// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1317, 1506 ] }
54,289
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777ERC20BaseToken
contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken { bool internal mErc20compatible; mapping(address => mapping(address => bool)) internal mAuthorized; mapping(address => mapping(address => uint256)) internal mAllowed; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible); _; } /// @notice For Backwards compatibility /// @return The decimls of the token. Forced to 18 in ERC777. function decimals() public erc20 constant returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) { return mAllowed[_owner][_spender]; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); if (mErc20compatible) { Transfer(_from, _to, _amount); } } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); if (mErc20compatible) { Transfer(_tokenHolder, 0x0, _amount); } } }
/** * @title ERC777ERC20BaseToken */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; }
/// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1822, 2236 ] }
54,290
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777ERC20BaseToken
contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken { bool internal mErc20compatible; mapping(address => mapping(address => bool)) internal mAuthorized; mapping(address => mapping(address => uint256)) internal mAllowed; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible); _; } /// @notice For Backwards compatibility /// @return The decimls of the token. Forced to 18 in ERC777. function decimals() public erc20 constant returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) { return mAllowed[_owner][_spender]; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); if (mErc20compatible) { Transfer(_from, _to, _amount); } } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); if (mErc20compatible) { Transfer(_tokenHolder, 0x0, _amount); } } }
/** * @title ERC777ERC20BaseToken */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; }
/// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 2600, 2824 ] }
54,291
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
ERC777ERC20BaseToken
contract ERC777ERC20BaseToken is ERC20Token, ERC777BaseToken { bool internal mErc20compatible; mapping(address => mapping(address => bool)) internal mAuthorized; mapping(address => mapping(address => uint256)) internal mAllowed; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators ) internal ERC777BaseToken(_name, _symbol, _granularity, _defaultOperators) { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /// @notice This modifier is applied to erc20 obsolete methods that are /// implemented only to maintain backwards compatibility. When the erc20 /// compatibility is disabled, this methods will fail. modifier erc20 () { require(mErc20compatible); _; } /// @notice For Backwards compatibility /// @return The decimls of the token. Forced to 18 in ERC777. function decimals() public erc20 constant returns (uint8) { return uint8(18); } /// @notice ERC20 backwards compatible transfer. /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, msg.sender, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible transferFrom. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The number of tokens to be transferred /// @return `true`, if the transfer can't be done, it should fail. function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(msg.sender, _from, _to, _amount, "", "", false); return true; } /// @notice ERC20 backwards compatible approve. /// `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. /// @param _spender The address of the account able to transfer the tokens /// @param _amount The number of tokens to be approved for transfer /// @return `true`, if the approve can't be done, it should fail. function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) { return mAllowed[_owner][_spender]; } function doSend( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { super.doSend(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); if (mErc20compatible) { Transfer(_from, _to, _amount); } } function doBurn(address _operator, address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) internal { super.doBurn(_operator, _tokenHolder, _amount, _holderData, _operatorData); if (mErc20compatible) { Transfer(_tokenHolder, 0x0, _amount); } } }
/** * @title ERC777ERC20BaseToken */
NatSpecMultiLine
allowance
function allowance(address _owner, address _spender) public erc20 constant returns (uint256 remaining) { return mAllowed[_owner][_spender]; }
/// @notice ERC20 backwards compatible allowance. /// This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 3196, 3356 ] }
54,292
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
InstallB
contract InstallB is ERC777ERC20BaseToken, Ownable { address private mBurnOperator; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators, address _burnOperator ) public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators) { mBurnOperator = _burnOperator; } /// @notice Disables the ERC20 interface. This function can only be called /// by the owner. function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); } /// @notice Re enables the ERC20 interface. This function can only be called /// by the owner. function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /* -- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- */ // /// @notice Generates `_amount` tokens to be assigned to `_tokenHolder` /// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. /// @param _tokenHolder The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @param _operatorData Data that will be passed to the recipient as a first transfer function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner { requireMultiple(_amount); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true); Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); } } /// @notice Burns `_amount` tokens from `_tokenHolder` /// Silly example of overriding the `burn` function to only let the owner burn its tokens. /// Do not forget to override the `burn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _amount The quantity of tokens to burn function burn(uint256 _amount, bytes _holderData) public onlyOwner { super.burn(_amount, _holderData); } /// @notice Burns `_amount` tokens from `_tokenHolder` by `_operator` /// Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens. /// Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _tokenHolder The address that will lose the tokens /// @param _amount The quantity of tokens to burn function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(msg.sender == mBurnOperator); super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData); } }
/** * @title ERC777 InstallB Contract */
NatSpecMultiLine
disableERC20
function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); }
/// @notice Disables the ERC20 interface. This function can only be called /// by the owner.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 500, 645 ] }
54,293
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
InstallB
contract InstallB is ERC777ERC20BaseToken, Ownable { address private mBurnOperator; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators, address _burnOperator ) public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators) { mBurnOperator = _burnOperator; } /// @notice Disables the ERC20 interface. This function can only be called /// by the owner. function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); } /// @notice Re enables the ERC20 interface. This function can only be called /// by the owner. function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /* -- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- */ // /// @notice Generates `_amount` tokens to be assigned to `_tokenHolder` /// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. /// @param _tokenHolder The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @param _operatorData Data that will be passed to the recipient as a first transfer function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner { requireMultiple(_amount); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true); Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); } } /// @notice Burns `_amount` tokens from `_tokenHolder` /// Silly example of overriding the `burn` function to only let the owner burn its tokens. /// Do not forget to override the `burn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _amount The quantity of tokens to burn function burn(uint256 _amount, bytes _holderData) public onlyOwner { super.burn(_amount, _holderData); } /// @notice Burns `_amount` tokens from `_tokenHolder` by `_operator` /// Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens. /// Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _tokenHolder The address that will lose the tokens /// @param _amount The quantity of tokens to burn function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(msg.sender == mBurnOperator); super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData); } }
/** * @title ERC777 InstallB Contract */
NatSpecMultiLine
enableERC20
function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); }
/// @notice Re enables the ERC20 interface. This function can only be called /// by the owner.
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 754, 898 ] }
54,294
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
InstallB
contract InstallB is ERC777ERC20BaseToken, Ownable { address private mBurnOperator; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators, address _burnOperator ) public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators) { mBurnOperator = _burnOperator; } /// @notice Disables the ERC20 interface. This function can only be called /// by the owner. function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); } /// @notice Re enables the ERC20 interface. This function can only be called /// by the owner. function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /* -- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- */ // /// @notice Generates `_amount` tokens to be assigned to `_tokenHolder` /// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. /// @param _tokenHolder The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @param _operatorData Data that will be passed to the recipient as a first transfer function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner { requireMultiple(_amount); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true); Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); } } /// @notice Burns `_amount` tokens from `_tokenHolder` /// Silly example of overriding the `burn` function to only let the owner burn its tokens. /// Do not forget to override the `burn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _amount The quantity of tokens to burn function burn(uint256 _amount, bytes _holderData) public onlyOwner { super.burn(_amount, _holderData); } /// @notice Burns `_amount` tokens from `_tokenHolder` by `_operator` /// Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens. /// Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _tokenHolder The address that will lose the tokens /// @param _amount The quantity of tokens to burn function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(msg.sender == mBurnOperator); super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData); } }
/** * @title ERC777 InstallB Contract */
NatSpecMultiLine
mint
function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner { requireMultiple(_amount); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true); Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); } }
/// @notice Generates `_amount` tokens to be assigned to `_tokenHolder` /// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. /// @param _tokenHolder The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @param _operatorData Data that will be passed to the recipient as a first transfer
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 1441, 1937 ] }
54,295
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
InstallB
contract InstallB is ERC777ERC20BaseToken, Ownable { address private mBurnOperator; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators, address _burnOperator ) public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators) { mBurnOperator = _burnOperator; } /// @notice Disables the ERC20 interface. This function can only be called /// by the owner. function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); } /// @notice Re enables the ERC20 interface. This function can only be called /// by the owner. function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /* -- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- */ // /// @notice Generates `_amount` tokens to be assigned to `_tokenHolder` /// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. /// @param _tokenHolder The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @param _operatorData Data that will be passed to the recipient as a first transfer function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner { requireMultiple(_amount); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true); Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); } } /// @notice Burns `_amount` tokens from `_tokenHolder` /// Silly example of overriding the `burn` function to only let the owner burn its tokens. /// Do not forget to override the `burn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _amount The quantity of tokens to burn function burn(uint256 _amount, bytes _holderData) public onlyOwner { super.burn(_amount, _holderData); } /// @notice Burns `_amount` tokens from `_tokenHolder` by `_operator` /// Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens. /// Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _tokenHolder The address that will lose the tokens /// @param _amount The quantity of tokens to burn function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(msg.sender == mBurnOperator); super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData); } }
/** * @title ERC777 InstallB Contract */
NatSpecMultiLine
burn
function burn(uint256 _amount, bytes _holderData) public onlyOwner { super.burn(_amount, _holderData); }
/// @notice Burns `_amount` tokens from `_tokenHolder` /// Silly example of overriding the `burn` function to only let the owner burn its tokens. /// Do not forget to override the `burn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _amount The quantity of tokens to burn
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 2297, 2420 ] }
54,296
InstallB
InstallB.sol
0x785a6da86aee8e5ca4e1e6073e684b10454225f5
Solidity
InstallB
contract InstallB is ERC777ERC20BaseToken, Ownable { address private mBurnOperator; constructor ( string _name, string _symbol, uint256 _granularity, address[] _defaultOperators, address _burnOperator ) public ERC777ERC20BaseToken(_name, _symbol, _granularity, _defaultOperators) { mBurnOperator = _burnOperator; } /// @notice Disables the ERC20 interface. This function can only be called /// by the owner. function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); } /// @notice Re enables the ERC20 interface. This function can only be called /// by the owner. function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /* -- Mint And Burn Functions (not part of the ERC777 standard, only the Events/tokensReceived call are) -- */ // /// @notice Generates `_amount` tokens to be assigned to `_tokenHolder` /// Sample mint function to showcase the use of the `Minted` event and the logic to notify the recipient. /// @param _tokenHolder The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @param _operatorData Data that will be passed to the recipient as a first transfer function mint(address _tokenHolder, uint256 _amount, bytes _operatorData) public onlyOwner { requireMultiple(_amount); mTotalSupply = mTotalSupply.add(_amount); mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount); callRecipient(msg.sender, 0x0, _tokenHolder, _amount, "", _operatorData, true); Minted(msg.sender, _tokenHolder, _amount, _operatorData); if (mErc20compatible) { Transfer(0x0, _tokenHolder, _amount); } } /// @notice Burns `_amount` tokens from `_tokenHolder` /// Silly example of overriding the `burn` function to only let the owner burn its tokens. /// Do not forget to override the `burn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _amount The quantity of tokens to burn function burn(uint256 _amount, bytes _holderData) public onlyOwner { super.burn(_amount, _holderData); } /// @notice Burns `_amount` tokens from `_tokenHolder` by `_operator` /// Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens. /// Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _tokenHolder The address that will lose the tokens /// @param _amount The quantity of tokens to burn function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(msg.sender == mBurnOperator); super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData); } }
/** * @title ERC777 InstallB Contract */
NatSpecMultiLine
operatorBurn
function operatorBurn(address _tokenHolder, uint256 _amount, bytes _holderData, bytes _operatorData) public { require(msg.sender == mBurnOperator); super.operatorBurn(_tokenHolder, _amount, _holderData, _operatorData); }
/// @notice Burns `_amount` tokens from `_tokenHolder` by `_operator` /// Silly example of overriding the `operatorBurn` function to only let a specific operator burn tokens. /// Do not forget to override the `operatorBurn` function in your token contract if you want to prevent users from /// burning their tokens. /// @param _tokenHolder The address that will lose the tokens /// @param _amount The quantity of tokens to burn
NatSpecSingleLine
v0.4.24+commit.e67f0147
bzzr://524d13f6ea7a977d425c4094d6fb9c551afdbf734bcec4370defc929bfd07112
{ "func_code_index": [ 2884, 3132 ] }
54,297
DAIPointsToken
contracts/DAIPointsToken.sol
0x50bb4200794fad114aeb1c3bdd1f7f9d72eaf607
Solidity
DAIPointsToken
contract DAIPointsToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, Ownable { using SafeMath for uint256; uint256 public DAI_TO_DAIPOINTS_CONVERSION_RATE = 100; IERC20 public DAI; constructor (address _dai) public ERC20Detailed('DAIPoints', 'DAIp', 18) { setDAI(_dai); } /** * @dev Function to be called by owner only to set the DAI token address * @param _address DAI token address */ function setDAI(address _address) public onlyOwner { require(_address != address(0) && Address.isContract(_address)); DAI = IERC20(_address); } /** * @dev Function to be called by owner only to set the DAI to DAIPoints conversion rate * @param _rate amount of DAIPoints equal to 1 DAI */ function setConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0); DAI_TO_DAIPOINTS_CONVERSION_RATE = _rate; } /** * @dev Get DAIPoints (minted) in exchange for DAI, according to the conversion rate * @param _amount amount (in wei) of DAI to be transferred from msg.sender balance to this contract's balance */ function getDAIPoints(uint256 _amount) public { require(DAI.transferFrom(msg.sender, address(this), _amount)); _mint(msg.sender, _amount.mul(DAI_TO_DAIPOINTS_CONVERSION_RATE)); } /** * @dev Get DAI in exchange for DAIPoints (burned), according to the conversion rate * @param _amount amount (in wei) of DAIPoints to be deducted from msg.sender balance */ function getDAI(uint256 _amount) public { _burn(msg.sender, _amount); require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), msg.sender, _amount.div(DAI_TO_DAIPOINTS_CONVERSION_RATE))); } /** * @dev Function to be called by owner only to transfer DAI (without exchange to DAIPoints) * @param _to address to transfer DAI from this contract * @param _amount amount (in wei) of DAI to be transferred from this contract */ function moveDAI(address _to, uint256 _amount) public onlyOwner { require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), _to, _amount)); } }
/** * @title DAIPoints token contract * @author LiorRabin */
NatSpecMultiLine
setDAI
function setDAI(address _address) public onlyOwner { require(_address != address(0) && Address.isContract(_address)); DAI = IERC20(_address); }
/** * @dev Function to be called by owner only to set the DAI token address * @param _address DAI token address */
NatSpecMultiLine
v0.5.2+commit.1df8f40c
MIT
bzzr://cdd13de40eea780ce847281e897f6d769605c7d4a6cfdda154f36249a7340126
{ "func_code_index": [ 445, 604 ] }
54,298
DAIPointsToken
contracts/DAIPointsToken.sol
0x50bb4200794fad114aeb1c3bdd1f7f9d72eaf607
Solidity
DAIPointsToken
contract DAIPointsToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, Ownable { using SafeMath for uint256; uint256 public DAI_TO_DAIPOINTS_CONVERSION_RATE = 100; IERC20 public DAI; constructor (address _dai) public ERC20Detailed('DAIPoints', 'DAIp', 18) { setDAI(_dai); } /** * @dev Function to be called by owner only to set the DAI token address * @param _address DAI token address */ function setDAI(address _address) public onlyOwner { require(_address != address(0) && Address.isContract(_address)); DAI = IERC20(_address); } /** * @dev Function to be called by owner only to set the DAI to DAIPoints conversion rate * @param _rate amount of DAIPoints equal to 1 DAI */ function setConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0); DAI_TO_DAIPOINTS_CONVERSION_RATE = _rate; } /** * @dev Get DAIPoints (minted) in exchange for DAI, according to the conversion rate * @param _amount amount (in wei) of DAI to be transferred from msg.sender balance to this contract's balance */ function getDAIPoints(uint256 _amount) public { require(DAI.transferFrom(msg.sender, address(this), _amount)); _mint(msg.sender, _amount.mul(DAI_TO_DAIPOINTS_CONVERSION_RATE)); } /** * @dev Get DAI in exchange for DAIPoints (burned), according to the conversion rate * @param _amount amount (in wei) of DAIPoints to be deducted from msg.sender balance */ function getDAI(uint256 _amount) public { _burn(msg.sender, _amount); require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), msg.sender, _amount.div(DAI_TO_DAIPOINTS_CONVERSION_RATE))); } /** * @dev Function to be called by owner only to transfer DAI (without exchange to DAIPoints) * @param _to address to transfer DAI from this contract * @param _amount amount (in wei) of DAI to be transferred from this contract */ function moveDAI(address _to, uint256 _amount) public onlyOwner { require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), _to, _amount)); } }
/** * @title DAIPoints token contract * @author LiorRabin */
NatSpecMultiLine
setConversionRate
function setConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0); DAI_TO_DAIPOINTS_CONVERSION_RATE = _rate; }
/** * @dev Function to be called by owner only to set the DAI to DAIPoints conversion rate * @param _rate amount of DAIPoints equal to 1 DAI */
NatSpecMultiLine
v0.5.2+commit.1df8f40c
MIT
bzzr://cdd13de40eea780ce847281e897f6d769605c7d4a6cfdda154f36249a7340126
{ "func_code_index": [ 763, 903 ] }
54,299
DAIPointsToken
contracts/DAIPointsToken.sol
0x50bb4200794fad114aeb1c3bdd1f7f9d72eaf607
Solidity
DAIPointsToken
contract DAIPointsToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, Ownable { using SafeMath for uint256; uint256 public DAI_TO_DAIPOINTS_CONVERSION_RATE = 100; IERC20 public DAI; constructor (address _dai) public ERC20Detailed('DAIPoints', 'DAIp', 18) { setDAI(_dai); } /** * @dev Function to be called by owner only to set the DAI token address * @param _address DAI token address */ function setDAI(address _address) public onlyOwner { require(_address != address(0) && Address.isContract(_address)); DAI = IERC20(_address); } /** * @dev Function to be called by owner only to set the DAI to DAIPoints conversion rate * @param _rate amount of DAIPoints equal to 1 DAI */ function setConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0); DAI_TO_DAIPOINTS_CONVERSION_RATE = _rate; } /** * @dev Get DAIPoints (minted) in exchange for DAI, according to the conversion rate * @param _amount amount (in wei) of DAI to be transferred from msg.sender balance to this contract's balance */ function getDAIPoints(uint256 _amount) public { require(DAI.transferFrom(msg.sender, address(this), _amount)); _mint(msg.sender, _amount.mul(DAI_TO_DAIPOINTS_CONVERSION_RATE)); } /** * @dev Get DAI in exchange for DAIPoints (burned), according to the conversion rate * @param _amount amount (in wei) of DAIPoints to be deducted from msg.sender balance */ function getDAI(uint256 _amount) public { _burn(msg.sender, _amount); require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), msg.sender, _amount.div(DAI_TO_DAIPOINTS_CONVERSION_RATE))); } /** * @dev Function to be called by owner only to transfer DAI (without exchange to DAIPoints) * @param _to address to transfer DAI from this contract * @param _amount amount (in wei) of DAI to be transferred from this contract */ function moveDAI(address _to, uint256 _amount) public onlyOwner { require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), _to, _amount)); } }
/** * @title DAIPoints token contract * @author LiorRabin */
NatSpecMultiLine
getDAIPoints
function getDAIPoints(uint256 _amount) public { require(DAI.transferFrom(msg.sender, address(this), _amount)); _mint(msg.sender, _amount.mul(DAI_TO_DAIPOINTS_CONVERSION_RATE)); }
/** * @dev Get DAIPoints (minted) in exchange for DAI, according to the conversion rate * @param _amount amount (in wei) of DAI to be transferred from msg.sender balance to this contract's balance */
NatSpecMultiLine
v0.5.2+commit.1df8f40c
MIT
bzzr://cdd13de40eea780ce847281e897f6d769605c7d4a6cfdda154f36249a7340126
{ "func_code_index": [ 1118, 1312 ] }
54,300
DAIPointsToken
contracts/DAIPointsToken.sol
0x50bb4200794fad114aeb1c3bdd1f7f9d72eaf607
Solidity
DAIPointsToken
contract DAIPointsToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, Ownable { using SafeMath for uint256; uint256 public DAI_TO_DAIPOINTS_CONVERSION_RATE = 100; IERC20 public DAI; constructor (address _dai) public ERC20Detailed('DAIPoints', 'DAIp', 18) { setDAI(_dai); } /** * @dev Function to be called by owner only to set the DAI token address * @param _address DAI token address */ function setDAI(address _address) public onlyOwner { require(_address != address(0) && Address.isContract(_address)); DAI = IERC20(_address); } /** * @dev Function to be called by owner only to set the DAI to DAIPoints conversion rate * @param _rate amount of DAIPoints equal to 1 DAI */ function setConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0); DAI_TO_DAIPOINTS_CONVERSION_RATE = _rate; } /** * @dev Get DAIPoints (minted) in exchange for DAI, according to the conversion rate * @param _amount amount (in wei) of DAI to be transferred from msg.sender balance to this contract's balance */ function getDAIPoints(uint256 _amount) public { require(DAI.transferFrom(msg.sender, address(this), _amount)); _mint(msg.sender, _amount.mul(DAI_TO_DAIPOINTS_CONVERSION_RATE)); } /** * @dev Get DAI in exchange for DAIPoints (burned), according to the conversion rate * @param _amount amount (in wei) of DAIPoints to be deducted from msg.sender balance */ function getDAI(uint256 _amount) public { _burn(msg.sender, _amount); require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), msg.sender, _amount.div(DAI_TO_DAIPOINTS_CONVERSION_RATE))); } /** * @dev Function to be called by owner only to transfer DAI (without exchange to DAIPoints) * @param _to address to transfer DAI from this contract * @param _amount amount (in wei) of DAI to be transferred from this contract */ function moveDAI(address _to, uint256 _amount) public onlyOwner { require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), _to, _amount)); } }
/** * @title DAIPoints token contract * @author LiorRabin */
NatSpecMultiLine
getDAI
function getDAI(uint256 _amount) public { _burn(msg.sender, _amount); require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), msg.sender, _amount.div(DAI_TO_DAIPOINTS_CONVERSION_RATE))); }
/** * @dev Get DAI in exchange for DAIPoints (burned), according to the conversion rate * @param _amount amount (in wei) of DAIPoints to be deducted from msg.sender balance */
NatSpecMultiLine
v0.5.2+commit.1df8f40c
MIT
bzzr://cdd13de40eea780ce847281e897f6d769605c7d4a6cfdda154f36249a7340126
{ "func_code_index": [ 1503, 1742 ] }
54,301
DAIPointsToken
contracts/DAIPointsToken.sol
0x50bb4200794fad114aeb1c3bdd1f7f9d72eaf607
Solidity
DAIPointsToken
contract DAIPointsToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, Ownable { using SafeMath for uint256; uint256 public DAI_TO_DAIPOINTS_CONVERSION_RATE = 100; IERC20 public DAI; constructor (address _dai) public ERC20Detailed('DAIPoints', 'DAIp', 18) { setDAI(_dai); } /** * @dev Function to be called by owner only to set the DAI token address * @param _address DAI token address */ function setDAI(address _address) public onlyOwner { require(_address != address(0) && Address.isContract(_address)); DAI = IERC20(_address); } /** * @dev Function to be called by owner only to set the DAI to DAIPoints conversion rate * @param _rate amount of DAIPoints equal to 1 DAI */ function setConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0); DAI_TO_DAIPOINTS_CONVERSION_RATE = _rate; } /** * @dev Get DAIPoints (minted) in exchange for DAI, according to the conversion rate * @param _amount amount (in wei) of DAI to be transferred from msg.sender balance to this contract's balance */ function getDAIPoints(uint256 _amount) public { require(DAI.transferFrom(msg.sender, address(this), _amount)); _mint(msg.sender, _amount.mul(DAI_TO_DAIPOINTS_CONVERSION_RATE)); } /** * @dev Get DAI in exchange for DAIPoints (burned), according to the conversion rate * @param _amount amount (in wei) of DAIPoints to be deducted from msg.sender balance */ function getDAI(uint256 _amount) public { _burn(msg.sender, _amount); require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), msg.sender, _amount.div(DAI_TO_DAIPOINTS_CONVERSION_RATE))); } /** * @dev Function to be called by owner only to transfer DAI (without exchange to DAIPoints) * @param _to address to transfer DAI from this contract * @param _amount amount (in wei) of DAI to be transferred from this contract */ function moveDAI(address _to, uint256 _amount) public onlyOwner { require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), _to, _amount)); } }
/** * @title DAIPoints token contract * @author LiorRabin */
NatSpecMultiLine
moveDAI
function moveDAI(address _to, uint256 _amount) public onlyOwner { require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), _to, _amount)); }
/** * @dev Function to be called by owner only to transfer DAI (without exchange to DAIPoints) * @param _to address to transfer DAI from this contract * @param _amount amount (in wei) of DAI to be transferred from this contract */
NatSpecMultiLine
v0.5.2+commit.1df8f40c
MIT
bzzr://cdd13de40eea780ce847281e897f6d769605c7d4a6cfdda154f36249a7340126
{ "func_code_index": [ 1991, 2176 ] }
54,302
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
DistrictsCoreInterface
contract DistrictsCoreInterface { // callable by other contracts to control economy function isDopeRaiderDistrictsCore() public pure returns (bool); function increaseDistrictWeed(uint256 _district, uint256 _quantity) public; function increaseDistrictCoke(uint256 _district, uint256 _quantity) public; function distributeRevenue(uint256 _district , uint8 _splitW, uint8 _splitC) public payable; function getNarcoLocation(uint256 _narcoId) public view returns (uint8 location); }
// DopeRaider Narcos Contract // by gasmasters.io // contact: [email protected]
LineComment
isDopeRaiderDistrictsCore
function isDopeRaiderDistrictsCore() public pure returns (bool);
// callable by other contracts to control economy
LineComment
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 88, 155 ] }
54,303
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoBase
contract NarcoBase is NarcoAccessControl { /*** EVENTS ***/ event NarcoCreated(address indexed owner, uint256 narcoId, string genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a narcos /// ownership is assigned, including newly created narcos. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /*** DATA TYPES ***/ // consumable indexes /* uint constant gasIndex = 0; uint constant seedsIndex = 1; uint constant chemicalsIndex = 2; uint constant ammoIndex = 3; // skills indexes - each skill can range from 1 - 10 in level uint constant speedIndex = 0; // speed of travel uint constant growIndex = 1; // speed/yield of grow uint constant refineIndex = 2; // refine coke uint constant attackIndex = 3; // attack uint constant defenseIndex = 4; // defense uint constant capacityIndex = 5; // how many items can be carried. // stat indexes uint constant dealsCompleted = 0; // dealsCompleted uint constant weedGrowCompleted = 1; // weedGrowCompleted uint constant cokeRefineCompleted = 2; // refineCompleted uint constant attacksSucceeded = 3; // attacksSucceeded uint constant defendedSuccessfully = 4; defendedSuccessfully uint constant raidsCompleted = 5; // raidsCompleted uint constant escapeHijack = 6; // escapeHijack uint constant travelling = 7; // traveller uint constant recruited = 8; // recruitment */ /// @dev The main Narco struct. Every narco in DopeRaider is represented by a copy /// of this structure. struct Narco { // The Narco's genetic code is packed into these 256-bits. string genes; // represents his avatar string narcoName; // items making level uint16 [9] stats; // inventory totals uint16 weedTotal; uint16 cokeTotal; uint8 [4] consumables; // gas, seeds, chemicals, ammo uint16 [6] skills; // travel time, grow, refine, attack, defend carry uint256 [6] cooldowns; // skill cooldown periods speed, grow, refine, attack, others if needed uint8 homeLocation; } /*** STORAGE ***/ /// @dev An array containing the Narco struct for all Narcos in existence. The ID /// of each narco is actually an index into this array. Narco[] narcos; /// @dev A mapping from narco IDs to the address that owns them. All narcos have /// some valid owner address, even gen0 narcos are created with a non-zero owner. mapping (uint256 => address) public narcoIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from NarcoIDs to an address that has been approved to call /// transferFrom(). A zero value means no approval is outstanding. mapping (uint256 => address) public narcoIndexToApproved; function _transfer(address _from, address _to, uint256 _tokenId) internal { // since the number of narcos is capped to 2^32 // there is no way to overflow this ownershipTokenCount[_to]++; narcoIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete narcoIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } // Will generate a new Narco and generate the event function _createNarco( string _genes, string _name, address _owner ) internal returns (uint) { uint16[6] memory randomskills= [ uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+31) ]; uint256[6] memory cools; uint16[9] memory nostats; Narco memory _narco = Narco({ genes: _genes, narcoName: _name, cooldowns: cools, stats: nostats, weedTotal: 0, cokeTotal: 0, consumables: [4,6,2,1], skills: randomskills, homeLocation: uint8(random(6)+1) }); uint256 newNarcoId = narcos.push(_narco) - 1; require(newNarcoId <= 4294967295); // raid character (token 0) live in 7 and have random special skills if (newNarcoId==0){ narcos[0].homeLocation=7; // in vice island narcos[0].skills[4]=800; // defense narcos[0].skills[5]=65535; // carry } NarcoCreated(_owner, newNarcoId, _narco.genes); _transfer(0, _owner, newNarcoId); return newNarcoId; } function subToZero(uint256 a, uint256 b) internal pure returns (uint256) { if (b <= a){ return a - b; }else{ return 0; } } function getRemainingCapacity(uint256 _narcoId) public view returns (uint16 capacity){ uint256 usedCapacity = narcos[_narcoId].weedTotal + narcos[_narcoId].cokeTotal + narcos[_narcoId].consumables[0]+narcos[_narcoId].consumables[1]+narcos[_narcoId].consumables[2]+narcos[_narcoId].consumables[3]; capacity = uint16(subToZero(uint256(narcos[_narcoId].skills[5]), usedCapacity)); } // respect it's called now function getLevel(uint256 _narcoId) public view returns (uint16 rank){ /* dealsCompleted = 0; // dealsCompleted weedGrowCompleted = 1; // weedGrowCompleted cokeRefineCompleted = 2; // refineCompleted attacksSucceeded = 3; // attacksSucceeded defendedSuccessfully = 4; defendedSuccessfully raidsCompleted = 5; // raidsCompleted escapeHijack = 6; // escapeHijack travel = 7; // travelling */ rank = (narcos[_narcoId].stats[0]/12)+ (narcos[_narcoId].stats[1]/4)+ (narcos[_narcoId].stats[2]/4)+ (narcos[_narcoId].stats[3]/6)+ (narcos[_narcoId].stats[4]/6)+ (narcos[_narcoId].stats[5]/1)+ (narcos[_narcoId].stats[7]/12) ; } // pseudo random - but does that matter? uint64 _seed = 0; function random(uint64 upper) private returns (uint64 randomNumber) { _seed = uint64(keccak256(keccak256(block.blockhash(block.number-1), _seed), now)); return _seed % upper; } // never call this from a contract /// @param _owner The owner whose tokens we are interested in. function narcosByOwner(address _owner) public view returns(uint256[] ownedNarcos) { uint256 tokenCount = ownershipTokenCount[_owner]; uint256 totalNarcos = narcos.length - 1; uint256[] memory result = new uint256[](tokenCount); uint256 narcoId; uint256 resultIndex=0; for (narcoId = 0; narcoId <= totalNarcos; narcoId++) { if (narcoIndexToOwner[narcoId] == _owner) { result[resultIndex] = narcoId; resultIndex++; } } return result; } }
/// @title Base contract for DopeRaider. Holds all common structs, events and base variables.
NatSpecSingleLine
_createNarco
function _createNarco( string _genes, string _name, address _owner ) internal returns (uint) { uint16[6] memory randomskills= [ uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+31) ]; uint256[6] memory cools; uint16[9] memory nostats; Narco memory _narco = Narco({ genes: _genes, narcoName: _name, cooldowns: cools, stats: nostats, weedTotal: 0, cokeTotal: 0, consumables: [4,6,2,1], skills: randomskills, homeLocation: uint8(random(6)+1) }); uint256 newNarcoId = narcos.push(_narco) - 1; require(newNarcoId <= 4294967295); // raid character (token 0) live in 7 and have random special skills if (newNarcoId==0){ narcos[0].homeLocation=7; // in vice island narcos[0].skills[4]=800; // defense narcos[0].skills[5]=65535; // carry } NarcoCreated(_owner, newNarcoId, _narco.genes); _transfer(0, _owner, newNarcoId); return newNarcoId; }
// Will generate a new Narco and generate the event
LineComment
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 3641, 4988 ] }
54,304
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoBase
contract NarcoBase is NarcoAccessControl { /*** EVENTS ***/ event NarcoCreated(address indexed owner, uint256 narcoId, string genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a narcos /// ownership is assigned, including newly created narcos. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /*** DATA TYPES ***/ // consumable indexes /* uint constant gasIndex = 0; uint constant seedsIndex = 1; uint constant chemicalsIndex = 2; uint constant ammoIndex = 3; // skills indexes - each skill can range from 1 - 10 in level uint constant speedIndex = 0; // speed of travel uint constant growIndex = 1; // speed/yield of grow uint constant refineIndex = 2; // refine coke uint constant attackIndex = 3; // attack uint constant defenseIndex = 4; // defense uint constant capacityIndex = 5; // how many items can be carried. // stat indexes uint constant dealsCompleted = 0; // dealsCompleted uint constant weedGrowCompleted = 1; // weedGrowCompleted uint constant cokeRefineCompleted = 2; // refineCompleted uint constant attacksSucceeded = 3; // attacksSucceeded uint constant defendedSuccessfully = 4; defendedSuccessfully uint constant raidsCompleted = 5; // raidsCompleted uint constant escapeHijack = 6; // escapeHijack uint constant travelling = 7; // traveller uint constant recruited = 8; // recruitment */ /// @dev The main Narco struct. Every narco in DopeRaider is represented by a copy /// of this structure. struct Narco { // The Narco's genetic code is packed into these 256-bits. string genes; // represents his avatar string narcoName; // items making level uint16 [9] stats; // inventory totals uint16 weedTotal; uint16 cokeTotal; uint8 [4] consumables; // gas, seeds, chemicals, ammo uint16 [6] skills; // travel time, grow, refine, attack, defend carry uint256 [6] cooldowns; // skill cooldown periods speed, grow, refine, attack, others if needed uint8 homeLocation; } /*** STORAGE ***/ /// @dev An array containing the Narco struct for all Narcos in existence. The ID /// of each narco is actually an index into this array. Narco[] narcos; /// @dev A mapping from narco IDs to the address that owns them. All narcos have /// some valid owner address, even gen0 narcos are created with a non-zero owner. mapping (uint256 => address) public narcoIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from NarcoIDs to an address that has been approved to call /// transferFrom(). A zero value means no approval is outstanding. mapping (uint256 => address) public narcoIndexToApproved; function _transfer(address _from, address _to, uint256 _tokenId) internal { // since the number of narcos is capped to 2^32 // there is no way to overflow this ownershipTokenCount[_to]++; narcoIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete narcoIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } // Will generate a new Narco and generate the event function _createNarco( string _genes, string _name, address _owner ) internal returns (uint) { uint16[6] memory randomskills= [ uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+31) ]; uint256[6] memory cools; uint16[9] memory nostats; Narco memory _narco = Narco({ genes: _genes, narcoName: _name, cooldowns: cools, stats: nostats, weedTotal: 0, cokeTotal: 0, consumables: [4,6,2,1], skills: randomskills, homeLocation: uint8(random(6)+1) }); uint256 newNarcoId = narcos.push(_narco) - 1; require(newNarcoId <= 4294967295); // raid character (token 0) live in 7 and have random special skills if (newNarcoId==0){ narcos[0].homeLocation=7; // in vice island narcos[0].skills[4]=800; // defense narcos[0].skills[5]=65535; // carry } NarcoCreated(_owner, newNarcoId, _narco.genes); _transfer(0, _owner, newNarcoId); return newNarcoId; } function subToZero(uint256 a, uint256 b) internal pure returns (uint256) { if (b <= a){ return a - b; }else{ return 0; } } function getRemainingCapacity(uint256 _narcoId) public view returns (uint16 capacity){ uint256 usedCapacity = narcos[_narcoId].weedTotal + narcos[_narcoId].cokeTotal + narcos[_narcoId].consumables[0]+narcos[_narcoId].consumables[1]+narcos[_narcoId].consumables[2]+narcos[_narcoId].consumables[3]; capacity = uint16(subToZero(uint256(narcos[_narcoId].skills[5]), usedCapacity)); } // respect it's called now function getLevel(uint256 _narcoId) public view returns (uint16 rank){ /* dealsCompleted = 0; // dealsCompleted weedGrowCompleted = 1; // weedGrowCompleted cokeRefineCompleted = 2; // refineCompleted attacksSucceeded = 3; // attacksSucceeded defendedSuccessfully = 4; defendedSuccessfully raidsCompleted = 5; // raidsCompleted escapeHijack = 6; // escapeHijack travel = 7; // travelling */ rank = (narcos[_narcoId].stats[0]/12)+ (narcos[_narcoId].stats[1]/4)+ (narcos[_narcoId].stats[2]/4)+ (narcos[_narcoId].stats[3]/6)+ (narcos[_narcoId].stats[4]/6)+ (narcos[_narcoId].stats[5]/1)+ (narcos[_narcoId].stats[7]/12) ; } // pseudo random - but does that matter? uint64 _seed = 0; function random(uint64 upper) private returns (uint64 randomNumber) { _seed = uint64(keccak256(keccak256(block.blockhash(block.number-1), _seed), now)); return _seed % upper; } // never call this from a contract /// @param _owner The owner whose tokens we are interested in. function narcosByOwner(address _owner) public view returns(uint256[] ownedNarcos) { uint256 tokenCount = ownershipTokenCount[_owner]; uint256 totalNarcos = narcos.length - 1; uint256[] memory result = new uint256[](tokenCount); uint256 narcoId; uint256 resultIndex=0; for (narcoId = 0; narcoId <= totalNarcos; narcoId++) { if (narcoIndexToOwner[narcoId] == _owner) { result[resultIndex] = narcoId; resultIndex++; } } return result; } }
/// @title Base contract for DopeRaider. Holds all common structs, events and base variables.
NatSpecSingleLine
getLevel
function getLevel(uint256 _narcoId) public view returns (uint16 rank){ /* dealsCompleted = 0; // dealsCompleted weedGrowCompleted = 1; // weedGrowCompleted cokeRefineCompleted = 2; // refineCompleted attacksSucceeded = 3; // attacksSucceeded defendedSuccessfully = 4; defendedSuccessfully raidsCompleted = 5; // raidsCompleted escapeHijack = 6; // escapeHijack travel = 7; // travelling */ rank = (narcos[_narcoId].stats[0]/12)+ (narcos[_narcoId].stats[1]/4)+ (narcos[_narcoId].stats[2]/4)+ (narcos[_narcoId].stats[3]/6)+ (narcos[_narcoId].stats[4]/6)+ (narcos[_narcoId].stats[5]/1)+ (narcos[_narcoId].stats[7]/12) ; }
// respect it's called now
LineComment
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 5619, 6453 ] }
54,305
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoBase
contract NarcoBase is NarcoAccessControl { /*** EVENTS ***/ event NarcoCreated(address indexed owner, uint256 narcoId, string genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a narcos /// ownership is assigned, including newly created narcos. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /*** DATA TYPES ***/ // consumable indexes /* uint constant gasIndex = 0; uint constant seedsIndex = 1; uint constant chemicalsIndex = 2; uint constant ammoIndex = 3; // skills indexes - each skill can range from 1 - 10 in level uint constant speedIndex = 0; // speed of travel uint constant growIndex = 1; // speed/yield of grow uint constant refineIndex = 2; // refine coke uint constant attackIndex = 3; // attack uint constant defenseIndex = 4; // defense uint constant capacityIndex = 5; // how many items can be carried. // stat indexes uint constant dealsCompleted = 0; // dealsCompleted uint constant weedGrowCompleted = 1; // weedGrowCompleted uint constant cokeRefineCompleted = 2; // refineCompleted uint constant attacksSucceeded = 3; // attacksSucceeded uint constant defendedSuccessfully = 4; defendedSuccessfully uint constant raidsCompleted = 5; // raidsCompleted uint constant escapeHijack = 6; // escapeHijack uint constant travelling = 7; // traveller uint constant recruited = 8; // recruitment */ /// @dev The main Narco struct. Every narco in DopeRaider is represented by a copy /// of this structure. struct Narco { // The Narco's genetic code is packed into these 256-bits. string genes; // represents his avatar string narcoName; // items making level uint16 [9] stats; // inventory totals uint16 weedTotal; uint16 cokeTotal; uint8 [4] consumables; // gas, seeds, chemicals, ammo uint16 [6] skills; // travel time, grow, refine, attack, defend carry uint256 [6] cooldowns; // skill cooldown periods speed, grow, refine, attack, others if needed uint8 homeLocation; } /*** STORAGE ***/ /// @dev An array containing the Narco struct for all Narcos in existence. The ID /// of each narco is actually an index into this array. Narco[] narcos; /// @dev A mapping from narco IDs to the address that owns them. All narcos have /// some valid owner address, even gen0 narcos are created with a non-zero owner. mapping (uint256 => address) public narcoIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from NarcoIDs to an address that has been approved to call /// transferFrom(). A zero value means no approval is outstanding. mapping (uint256 => address) public narcoIndexToApproved; function _transfer(address _from, address _to, uint256 _tokenId) internal { // since the number of narcos is capped to 2^32 // there is no way to overflow this ownershipTokenCount[_to]++; narcoIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete narcoIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } // Will generate a new Narco and generate the event function _createNarco( string _genes, string _name, address _owner ) internal returns (uint) { uint16[6] memory randomskills= [ uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+1), uint16(random(9)+31) ]; uint256[6] memory cools; uint16[9] memory nostats; Narco memory _narco = Narco({ genes: _genes, narcoName: _name, cooldowns: cools, stats: nostats, weedTotal: 0, cokeTotal: 0, consumables: [4,6,2,1], skills: randomskills, homeLocation: uint8(random(6)+1) }); uint256 newNarcoId = narcos.push(_narco) - 1; require(newNarcoId <= 4294967295); // raid character (token 0) live in 7 and have random special skills if (newNarcoId==0){ narcos[0].homeLocation=7; // in vice island narcos[0].skills[4]=800; // defense narcos[0].skills[5]=65535; // carry } NarcoCreated(_owner, newNarcoId, _narco.genes); _transfer(0, _owner, newNarcoId); return newNarcoId; } function subToZero(uint256 a, uint256 b) internal pure returns (uint256) { if (b <= a){ return a - b; }else{ return 0; } } function getRemainingCapacity(uint256 _narcoId) public view returns (uint16 capacity){ uint256 usedCapacity = narcos[_narcoId].weedTotal + narcos[_narcoId].cokeTotal + narcos[_narcoId].consumables[0]+narcos[_narcoId].consumables[1]+narcos[_narcoId].consumables[2]+narcos[_narcoId].consumables[3]; capacity = uint16(subToZero(uint256(narcos[_narcoId].skills[5]), usedCapacity)); } // respect it's called now function getLevel(uint256 _narcoId) public view returns (uint16 rank){ /* dealsCompleted = 0; // dealsCompleted weedGrowCompleted = 1; // weedGrowCompleted cokeRefineCompleted = 2; // refineCompleted attacksSucceeded = 3; // attacksSucceeded defendedSuccessfully = 4; defendedSuccessfully raidsCompleted = 5; // raidsCompleted escapeHijack = 6; // escapeHijack travel = 7; // travelling */ rank = (narcos[_narcoId].stats[0]/12)+ (narcos[_narcoId].stats[1]/4)+ (narcos[_narcoId].stats[2]/4)+ (narcos[_narcoId].stats[3]/6)+ (narcos[_narcoId].stats[4]/6)+ (narcos[_narcoId].stats[5]/1)+ (narcos[_narcoId].stats[7]/12) ; } // pseudo random - but does that matter? uint64 _seed = 0; function random(uint64 upper) private returns (uint64 randomNumber) { _seed = uint64(keccak256(keccak256(block.blockhash(block.number-1), _seed), now)); return _seed % upper; } // never call this from a contract /// @param _owner The owner whose tokens we are interested in. function narcosByOwner(address _owner) public view returns(uint256[] ownedNarcos) { uint256 tokenCount = ownershipTokenCount[_owner]; uint256 totalNarcos = narcos.length - 1; uint256[] memory result = new uint256[](tokenCount); uint256 narcoId; uint256 resultIndex=0; for (narcoId = 0; narcoId <= totalNarcos; narcoId++) { if (narcoIndexToOwner[narcoId] == _owner) { result[resultIndex] = narcoId; resultIndex++; } } return result; } }
/// @title Base contract for DopeRaider. Holds all common structs, events and base variables.
NatSpecSingleLine
narcosByOwner
function narcosByOwner(address _owner) public view returns(uint256[] ownedNarcos) { uint256 tokenCount = ownershipTokenCount[_owner]; uint256 totalNarcos = narcos.length - 1; uint256[] memory result = new uint256[](tokenCount); uint256 narcoId; uint256 resultIndex=0; for (narcoId = 0; narcoId <= totalNarcos; narcoId++) { if (narcoIndexToOwner[narcoId] == _owner) { result[resultIndex] = narcoId; resultIndex++; } } return result; }
/// @param _owner The owner whose tokens we are interested in.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 6841, 7403 ] }
54,306
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoOwnership
contract NarcoOwnership is NarcoBase, ERC721 { string public name = "DopeRaider"; string public symbol = "DOPR"; function implementsERC721() public pure returns (bool) { return true; } /// @dev Checks if a given address is the current owner of a particular narco. /// @param _claimant the address we are validating against. /// @param _tokenId narco id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular narco. /// @param _claimant the address we are confirming narco is approved for. /// @param _tokenId narco id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. function _approve(uint256 _tokenId, address _approved) internal { narcoIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of narcos owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a narco to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// DopeRaider specifically) or your narco may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the narco to transfer. function transfer( address _to, uint256 _tokenId ) public { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific narco via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the narco that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a narco owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the narco to be transfered. /// @param _to The address that should take ownership of the narco. Can be any address, /// including the caller. /// @param _tokenId The ID of the narco to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(_to != address(0)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return narcos.length - 1; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = narcoIndexToOwner[_tokenId]; require(owner != address(0)); } }
/// @title The facet of the DopeRaider core contract that manages ownership, ERC-721 (draft) compliant.
NatSpecSingleLine
_owns
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToOwner[_tokenId] == _claimant; }
/// @dev Checks if a given address is the current owner of a particular narco. /// @param _claimant the address we are validating against. /// @param _tokenId narco id, only valid when > 0
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 428, 580 ] }
54,307
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoOwnership
contract NarcoOwnership is NarcoBase, ERC721 { string public name = "DopeRaider"; string public symbol = "DOPR"; function implementsERC721() public pure returns (bool) { return true; } /// @dev Checks if a given address is the current owner of a particular narco. /// @param _claimant the address we are validating against. /// @param _tokenId narco id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular narco. /// @param _claimant the address we are confirming narco is approved for. /// @param _tokenId narco id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. function _approve(uint256 _tokenId, address _approved) internal { narcoIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of narcos owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a narco to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// DopeRaider specifically) or your narco may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the narco to transfer. function transfer( address _to, uint256 _tokenId ) public { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific narco via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the narco that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a narco owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the narco to be transfered. /// @param _to The address that should take ownership of the narco. Can be any address, /// including the caller. /// @param _tokenId The ID of the narco to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(_to != address(0)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return narcos.length - 1; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = narcoIndexToOwner[_tokenId]; require(owner != address(0)); } }
/// @title The facet of the DopeRaider core contract that manages ownership, ERC-721 (draft) compliant.
NatSpecSingleLine
_approvedFor
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; }
/// @dev Checks if a given address currently has transferApproval for a particular narco. /// @param _claimant the address we are confirming narco is approved for. /// @param _tokenId narco id, only valid when > 0
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 812, 974 ] }
54,308
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoOwnership
contract NarcoOwnership is NarcoBase, ERC721 { string public name = "DopeRaider"; string public symbol = "DOPR"; function implementsERC721() public pure returns (bool) { return true; } /// @dev Checks if a given address is the current owner of a particular narco. /// @param _claimant the address we are validating against. /// @param _tokenId narco id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular narco. /// @param _claimant the address we are confirming narco is approved for. /// @param _tokenId narco id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. function _approve(uint256 _tokenId, address _approved) internal { narcoIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of narcos owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a narco to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// DopeRaider specifically) or your narco may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the narco to transfer. function transfer( address _to, uint256 _tokenId ) public { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific narco via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the narco that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a narco owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the narco to be transfered. /// @param _to The address that should take ownership of the narco. Can be any address, /// including the caller. /// @param _tokenId The ID of the narco to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(_to != address(0)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return narcos.length - 1; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = narcoIndexToOwner[_tokenId]; require(owner != address(0)); } }
/// @title The facet of the DopeRaider core contract that manages ownership, ERC-721 (draft) compliant.
NatSpecSingleLine
_approve
function _approve(uint256 _tokenId, address _approved) internal { narcoIndexToApproved[_tokenId] = _approved; }
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 1214, 1344 ] }
54,309
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoOwnership
contract NarcoOwnership is NarcoBase, ERC721 { string public name = "DopeRaider"; string public symbol = "DOPR"; function implementsERC721() public pure returns (bool) { return true; } /// @dev Checks if a given address is the current owner of a particular narco. /// @param _claimant the address we are validating against. /// @param _tokenId narco id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular narco. /// @param _claimant the address we are confirming narco is approved for. /// @param _tokenId narco id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. function _approve(uint256 _tokenId, address _approved) internal { narcoIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of narcos owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a narco to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// DopeRaider specifically) or your narco may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the narco to transfer. function transfer( address _to, uint256 _tokenId ) public { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific narco via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the narco that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a narco owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the narco to be transfered. /// @param _to The address that should take ownership of the narco. Can be any address, /// including the caller. /// @param _tokenId The ID of the narco to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(_to != address(0)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return narcos.length - 1; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = narcoIndexToOwner[_tokenId]; require(owner != address(0)); } }
/// @title The facet of the DopeRaider core contract that manages ownership, ERC-721 (draft) compliant.
NatSpecSingleLine
balanceOf
function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; }
/// @notice Returns the number of narcos owned by a specific address. /// @param _owner The owner address to check.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 1475, 1604 ] }
54,310
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoOwnership
contract NarcoOwnership is NarcoBase, ERC721 { string public name = "DopeRaider"; string public symbol = "DOPR"; function implementsERC721() public pure returns (bool) { return true; } /// @dev Checks if a given address is the current owner of a particular narco. /// @param _claimant the address we are validating against. /// @param _tokenId narco id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular narco. /// @param _claimant the address we are confirming narco is approved for. /// @param _tokenId narco id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. function _approve(uint256 _tokenId, address _approved) internal { narcoIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of narcos owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a narco to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// DopeRaider specifically) or your narco may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the narco to transfer. function transfer( address _to, uint256 _tokenId ) public { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific narco via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the narco that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a narco owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the narco to be transfered. /// @param _to The address that should take ownership of the narco. Can be any address, /// including the caller. /// @param _tokenId The ID of the narco to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(_to != address(0)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return narcos.length - 1; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = narcoIndexToOwner[_tokenId]; require(owner != address(0)); } }
/// @title The facet of the DopeRaider core contract that manages ownership, ERC-721 (draft) compliant.
NatSpecSingleLine
transfer
function transfer( address _to, uint256 _tokenId ) public { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); }
/// @notice Transfers a narco to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// DopeRaider specifically) or your narco may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the narco to transfer.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 1982, 2225 ] }
54,311
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoOwnership
contract NarcoOwnership is NarcoBase, ERC721 { string public name = "DopeRaider"; string public symbol = "DOPR"; function implementsERC721() public pure returns (bool) { return true; } /// @dev Checks if a given address is the current owner of a particular narco. /// @param _claimant the address we are validating against. /// @param _tokenId narco id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular narco. /// @param _claimant the address we are confirming narco is approved for. /// @param _tokenId narco id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. function _approve(uint256 _tokenId, address _approved) internal { narcoIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of narcos owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a narco to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// DopeRaider specifically) or your narco may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the narco to transfer. function transfer( address _to, uint256 _tokenId ) public { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific narco via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the narco that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a narco owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the narco to be transfered. /// @param _to The address that should take ownership of the narco. Can be any address, /// including the caller. /// @param _tokenId The ID of the narco to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(_to != address(0)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return narcos.length - 1; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = narcoIndexToOwner[_tokenId]; require(owner != address(0)); } }
/// @title The facet of the DopeRaider core contract that manages ownership, ERC-721 (draft) compliant.
NatSpecSingleLine
approve
function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); }
/// @notice Grant another address the right to transfer a specific narco via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the narco that can be transferred if this call succeeds.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 2605, 2845 ] }
54,312
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoOwnership
contract NarcoOwnership is NarcoBase, ERC721 { string public name = "DopeRaider"; string public symbol = "DOPR"; function implementsERC721() public pure returns (bool) { return true; } /// @dev Checks if a given address is the current owner of a particular narco. /// @param _claimant the address we are validating against. /// @param _tokenId narco id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular narco. /// @param _claimant the address we are confirming narco is approved for. /// @param _tokenId narco id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return narcoIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. function _approve(uint256 _tokenId, address _approved) internal { narcoIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of narcos owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a narco to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// DopeRaider specifically) or your narco may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the narco to transfer. function transfer( address _to, uint256 _tokenId ) public { require(_to != address(0)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific narco via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the narco that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a narco owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the narco to be transfered. /// @param _to The address that should take ownership of the narco. Can be any address, /// including the caller. /// @param _tokenId The ID of the narco to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(_to != address(0)); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return narcos.length - 1; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = narcoIndexToOwner[_tokenId]; require(owner != address(0)); } }
/// @title The facet of the DopeRaider core contract that manages ownership, ERC-721 (draft) compliant.
NatSpecSingleLine
transferFrom
function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(_to != address(0)); _transfer(_from, _to, _tokenId); }
/// @notice Transfer a narco owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the narco to be transfered. /// @param _to The address that should take ownership of the narco. Can be any address, /// including the caller. /// @param _tokenId The ID of the narco to be transferred.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 3269, 3584 ] }
54,313
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoAuction
contract NarcoAuction is NarcoUpdates { SaleClockAuction public saleAuction; function setSaleAuctionAddress(address _address) public onlyCLevel { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } function createSaleAuction( uint256 _narcoId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) public whenNotPaused { // Auction contract checks input sizes // If narco is already on any auction, this will throw // because it will be owned by the auction contract require(_owns(msg.sender, _narcoId)); _approve(_narcoId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer approval after escrowing the narco. saleAuction.createAuction( _narcoId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Transfers the balance of the sale auction contract /// to the DopeRaiderCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); } }
/// @title Handles creating auctions for sale of narcos. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction.
NatSpecSingleLine
withdrawAuctionBalances
function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); }
/// @dev Transfers the balance of the sale auction contract /// to the DopeRaiderCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 1315, 1423 ] }
54,314
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoMinting
contract NarcoMinting is NarcoAuction { // Limits the number of narcos the contract owner can ever create. uint256 public promoCreationLimit = 200; uint256 public gen0CreationLimit = 5000; // Constants for gen0 auctions. uint256 public gen0StartingPrice = 1 ether; uint256 public gen0EndingPrice = 20 finney; uint256 public gen0AuctionDuration = 1 days; // Counts the number of narcos the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo narco, up to a limit function createPromoNarco( string _genes, string _name, address _owner ) public onlyCLevel { if (_owner == address(0)) { _owner = cooAddress; } require(promoCreatedCount < promoCreationLimit); require(gen0CreatedCount < gen0CreationLimit); promoCreatedCount++; gen0CreatedCount++; _createNarco(_genes, _name, _owner); } /// @dev Creates a new gen0 narco with the given genes and /// creates an auction for it. function createGen0Auction( string _genes, string _name ) public onlyCLevel { require(gen0CreatedCount < gen0CreationLimit); uint256 narcoId = _createNarco(_genes,_name,address(this)); _approve(narcoId, saleAuction); saleAuction.createAuction( narcoId, _computeNextGen0Price(), gen0EndingPrice, gen0AuctionDuration, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 4 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1). require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; } return nextPrice; } }
/// @title all functions related to creating narcos
NatSpecSingleLine
createPromoNarco
function createPromoNarco( string _genes, string _name, address _owner ) public onlyCLevel { if (_owner == address(0)) { _owner = cooAddress; } require(promoCreatedCount < promoCreationLimit); require(gen0CreatedCount < gen0CreationLimit); promoCreatedCount++; gen0CreatedCount++; _createNarco(_genes, _name, _owner); }
/// @dev we can create promo narco, up to a limit
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 598, 1040 ] }
54,315
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoMinting
contract NarcoMinting is NarcoAuction { // Limits the number of narcos the contract owner can ever create. uint256 public promoCreationLimit = 200; uint256 public gen0CreationLimit = 5000; // Constants for gen0 auctions. uint256 public gen0StartingPrice = 1 ether; uint256 public gen0EndingPrice = 20 finney; uint256 public gen0AuctionDuration = 1 days; // Counts the number of narcos the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo narco, up to a limit function createPromoNarco( string _genes, string _name, address _owner ) public onlyCLevel { if (_owner == address(0)) { _owner = cooAddress; } require(promoCreatedCount < promoCreationLimit); require(gen0CreatedCount < gen0CreationLimit); promoCreatedCount++; gen0CreatedCount++; _createNarco(_genes, _name, _owner); } /// @dev Creates a new gen0 narco with the given genes and /// creates an auction for it. function createGen0Auction( string _genes, string _name ) public onlyCLevel { require(gen0CreatedCount < gen0CreationLimit); uint256 narcoId = _createNarco(_genes,_name,address(this)); _approve(narcoId, saleAuction); saleAuction.createAuction( narcoId, _computeNextGen0Price(), gen0EndingPrice, gen0AuctionDuration, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 4 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1). require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; } return nextPrice; } }
/// @title all functions related to creating narcos
NatSpecSingleLine
createGen0Auction
function createGen0Auction( string _genes, string _name ) public onlyCLevel { require(gen0CreatedCount < gen0CreationLimit); uint256 narcoId = _createNarco(_genes,_name,address(this)); _approve(narcoId, saleAuction); saleAuction.createAuction( narcoId, _computeNextGen0Price(), gen0EndingPrice, gen0AuctionDuration, address(this) ); gen0CreatedCount++; }
/// @dev Creates a new gen0 narco with the given genes and /// creates an auction for it.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 1144, 1657 ] }
54,316
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
NarcoMinting
contract NarcoMinting is NarcoAuction { // Limits the number of narcos the contract owner can ever create. uint256 public promoCreationLimit = 200; uint256 public gen0CreationLimit = 5000; // Constants for gen0 auctions. uint256 public gen0StartingPrice = 1 ether; uint256 public gen0EndingPrice = 20 finney; uint256 public gen0AuctionDuration = 1 days; // Counts the number of narcos the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo narco, up to a limit function createPromoNarco( string _genes, string _name, address _owner ) public onlyCLevel { if (_owner == address(0)) { _owner = cooAddress; } require(promoCreatedCount < promoCreationLimit); require(gen0CreatedCount < gen0CreationLimit); promoCreatedCount++; gen0CreatedCount++; _createNarco(_genes, _name, _owner); } /// @dev Creates a new gen0 narco with the given genes and /// creates an auction for it. function createGen0Auction( string _genes, string _name ) public onlyCLevel { require(gen0CreatedCount < gen0CreationLimit); uint256 narcoId = _createNarco(_genes,_name,address(this)); _approve(narcoId, saleAuction); saleAuction.createAuction( narcoId, _computeNextGen0Price(), gen0EndingPrice, gen0AuctionDuration, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 4 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1). require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; } return nextPrice; } }
/// @title all functions related to creating narcos
NatSpecSingleLine
_computeNextGen0Price
function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1). require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; } return nextPrice; }
/// @dev Computes the next gen0 auction starting price, given /// the average of the past 4 prices + 50%.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 1777, 2333 ] }
54,317
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
DopeRaiderCore
contract DopeRaiderCore is NarcoMinting { // This is the main DopeRaider contract. We have several seperately-instantiated contracts // that handle auctions, districts and the creation of new narcos. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // narco ownership. // // - NarcoBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - NarcoAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - NarcoOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - NarcoUpdates: This file contains the methods necessary to allow a separate contract to update narco stats // // - NarcoAuction: Here we have the public methods for auctioning or bidding on narcos. // The actual auction functionality is handled in a sibling sales contract, // while auction creation and bidding is mostly mediated through this facet of the core contract. // // - NarcoMinting: This final facet contains the functionality we use for creating new gen0 narcos. // We can make up to 4096 "promo" narcos // Set in case the core contract is broken and an upgrade is required address public newContractAddress; bool public gamePaused = true; modifier whenGameNotPaused() { require(!gamePaused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenGamePaused { require(gamePaused); _; } function pause() public onlyCLevel whenGameNotPaused { gamePaused = true; } function unpause() public onlyCLevel whenGamePaused { // can't unpause if contract was upgraded gamePaused = false; } // EVENTS event GrowWeedCompleted(uint256 indexed narcoId, uint yield); event RefineCokeCompleted(uint256 indexed narcoId, uint yield); function DopeRaiderCore() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) public onlyCLevel whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require(msg.sender == address(saleAuction)); } /// @param _id The ID of the narco of interest. function getNarco(uint256 _id) public view returns ( string narcoName, uint256 weedTotal, uint256 cokeTotal, uint16[6] skills, uint8[4] consumables, string genes, uint8 homeLocation, uint16 level, uint256[6] cooldowns, uint256 id, uint16 [9] stats ) { Narco storage narco = narcos[_id]; narcoName = narco.narcoName; weedTotal = narco.weedTotal; cokeTotal = narco.cokeTotal; skills = narco.skills; consumables = narco.consumables; genes = narco.genes; homeLocation = narco.homeLocation; level = getLevel(_id); cooldowns = narco.cooldowns; id = _id; stats = narco.stats; } uint256 public changeIdentityNarcoRespect = 30; function setChangeIdentityNarcoRespect(uint256 _respect) public onlyCLevel { changeIdentityNarcoRespect=_respect; } uint256 public personalisationCost = 0.01 ether; // pimp my narco function setPersonalisationCost(uint256 _cost) public onlyCLevel { personalisationCost=_cost; } function updateNarco(uint256 _narcoId, string _genes, string _name) public payable whenGameNotPaused { require(getLevel(_narcoId)>=changeIdentityNarcoRespect); // minimum level to recruit a narco require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=personalisationCost); narcos[_narcoId].genes = _genes; narcos[_narcoId].narcoName = _name; } uint256 public respectRequiredToRecruit = 150; function setRespectRequiredToRecruit(uint256 _respect) public onlyCLevel { respectRequiredToRecruit=_respect; } function recruitNarco(uint256 _narcoId, string _genes, string _name) public whenGameNotPaused { require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(getLevel(_narcoId)>=respectRequiredToRecruit); // minimum level to recruit a narco require(narcos[_narcoId].stats[8]<getLevel(_narcoId)/respectRequiredToRecruit); // must have recruited < respect / required reqpect (times) _createNarco(_genes,_name, msg.sender); narcos[_narcoId].stats[8]+=1; // increase number recruited } // crafting section uint256 public growCost = 0.003 ether; function setGrowCost(uint256 _cost) public onlyCLevel{ growCost=_cost; } function growWeed(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=growCost); require(now>narcos[_narcoId].cooldowns[1]); //cooldown must have expired uint16 growSkillLevel = narcos[_narcoId].skills[1]; // grow uint16 maxYield = 9 + growSkillLevel; // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[1],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting uint256 cooldown = now + ((910-(10*growSkillLevel))* 1 seconds); //calculate cooldown switch to minutes later narcos[_narcoId].cooldowns[1]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[1]=uint8(subToZero(uint256(narcos[_narcoId].consumables[1]),yield)); narcos[_narcoId].weedTotal+=uint8(yield); narcos[_narcoId].stats[1]+=1; // update the statistic for grow districtsCore.increaseDistrictWeed(district , yield); districtsCore.distributeRevenue.value(growCost)(uint256(district),50,50); // distribute the revenue to districts pots GrowWeedCompleted(_narcoId, yield); // notification event } uint256 public refineCost = 0.003 ether; function setRefineCost(uint256 _cost) public onlyCLevel{ refineCost=_cost; } function refineCoke(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=refineCost); require(now>narcos[_narcoId].cooldowns[2]); //cooldown must have expired uint16 refineSkillLevel = narcos[_narcoId].skills[2]; // refine uint16 maxYield = 3+(refineSkillLevel/3); // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[2],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting // uint256 cooldown = now + min(3 minutes,((168-(2*refineSkillLevel))* 1 seconds)); // calculate cooldown uint256 cooldown = now + ((910-(10*refineSkillLevel))* 1 seconds); // calculate cooldown narcos[_narcoId].cooldowns[2]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[2]=uint8(subToZero(uint256(narcos[_narcoId].consumables[2]),yield)); narcos[_narcoId].cokeTotal+=uint8(yield); narcos[_narcoId].stats[2]+=1; districtsCore.increaseDistrictCoke(district, yield); districtsCore.distributeRevenue.value(refineCost)(uint256(district),50,50); // distribute the revenue to districts pots RefineCokeCompleted(_narcoId, yield); // notification event } function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
/// @title DopeRaider: Collectible, narcos on the Ethereum blockchain. /// @dev The main DopeRaider contract
NatSpecSingleLine
setNewAddress
function setNewAddress(address _v2Address) public onlyCLevel whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); }
/// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 3058, 3223 ] }
54,318
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
DopeRaiderCore
contract DopeRaiderCore is NarcoMinting { // This is the main DopeRaider contract. We have several seperately-instantiated contracts // that handle auctions, districts and the creation of new narcos. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // narco ownership. // // - NarcoBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - NarcoAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - NarcoOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - NarcoUpdates: This file contains the methods necessary to allow a separate contract to update narco stats // // - NarcoAuction: Here we have the public methods for auctioning or bidding on narcos. // The actual auction functionality is handled in a sibling sales contract, // while auction creation and bidding is mostly mediated through this facet of the core contract. // // - NarcoMinting: This final facet contains the functionality we use for creating new gen0 narcos. // We can make up to 4096 "promo" narcos // Set in case the core contract is broken and an upgrade is required address public newContractAddress; bool public gamePaused = true; modifier whenGameNotPaused() { require(!gamePaused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenGamePaused { require(gamePaused); _; } function pause() public onlyCLevel whenGameNotPaused { gamePaused = true; } function unpause() public onlyCLevel whenGamePaused { // can't unpause if contract was upgraded gamePaused = false; } // EVENTS event GrowWeedCompleted(uint256 indexed narcoId, uint yield); event RefineCokeCompleted(uint256 indexed narcoId, uint yield); function DopeRaiderCore() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) public onlyCLevel whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require(msg.sender == address(saleAuction)); } /// @param _id The ID of the narco of interest. function getNarco(uint256 _id) public view returns ( string narcoName, uint256 weedTotal, uint256 cokeTotal, uint16[6] skills, uint8[4] consumables, string genes, uint8 homeLocation, uint16 level, uint256[6] cooldowns, uint256 id, uint16 [9] stats ) { Narco storage narco = narcos[_id]; narcoName = narco.narcoName; weedTotal = narco.weedTotal; cokeTotal = narco.cokeTotal; skills = narco.skills; consumables = narco.consumables; genes = narco.genes; homeLocation = narco.homeLocation; level = getLevel(_id); cooldowns = narco.cooldowns; id = _id; stats = narco.stats; } uint256 public changeIdentityNarcoRespect = 30; function setChangeIdentityNarcoRespect(uint256 _respect) public onlyCLevel { changeIdentityNarcoRespect=_respect; } uint256 public personalisationCost = 0.01 ether; // pimp my narco function setPersonalisationCost(uint256 _cost) public onlyCLevel { personalisationCost=_cost; } function updateNarco(uint256 _narcoId, string _genes, string _name) public payable whenGameNotPaused { require(getLevel(_narcoId)>=changeIdentityNarcoRespect); // minimum level to recruit a narco require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=personalisationCost); narcos[_narcoId].genes = _genes; narcos[_narcoId].narcoName = _name; } uint256 public respectRequiredToRecruit = 150; function setRespectRequiredToRecruit(uint256 _respect) public onlyCLevel { respectRequiredToRecruit=_respect; } function recruitNarco(uint256 _narcoId, string _genes, string _name) public whenGameNotPaused { require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(getLevel(_narcoId)>=respectRequiredToRecruit); // minimum level to recruit a narco require(narcos[_narcoId].stats[8]<getLevel(_narcoId)/respectRequiredToRecruit); // must have recruited < respect / required reqpect (times) _createNarco(_genes,_name, msg.sender); narcos[_narcoId].stats[8]+=1; // increase number recruited } // crafting section uint256 public growCost = 0.003 ether; function setGrowCost(uint256 _cost) public onlyCLevel{ growCost=_cost; } function growWeed(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=growCost); require(now>narcos[_narcoId].cooldowns[1]); //cooldown must have expired uint16 growSkillLevel = narcos[_narcoId].skills[1]; // grow uint16 maxYield = 9 + growSkillLevel; // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[1],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting uint256 cooldown = now + ((910-(10*growSkillLevel))* 1 seconds); //calculate cooldown switch to minutes later narcos[_narcoId].cooldowns[1]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[1]=uint8(subToZero(uint256(narcos[_narcoId].consumables[1]),yield)); narcos[_narcoId].weedTotal+=uint8(yield); narcos[_narcoId].stats[1]+=1; // update the statistic for grow districtsCore.increaseDistrictWeed(district , yield); districtsCore.distributeRevenue.value(growCost)(uint256(district),50,50); // distribute the revenue to districts pots GrowWeedCompleted(_narcoId, yield); // notification event } uint256 public refineCost = 0.003 ether; function setRefineCost(uint256 _cost) public onlyCLevel{ refineCost=_cost; } function refineCoke(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=refineCost); require(now>narcos[_narcoId].cooldowns[2]); //cooldown must have expired uint16 refineSkillLevel = narcos[_narcoId].skills[2]; // refine uint16 maxYield = 3+(refineSkillLevel/3); // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[2],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting // uint256 cooldown = now + min(3 minutes,((168-(2*refineSkillLevel))* 1 seconds)); // calculate cooldown uint256 cooldown = now + ((910-(10*refineSkillLevel))* 1 seconds); // calculate cooldown narcos[_narcoId].cooldowns[2]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[2]=uint8(subToZero(uint256(narcos[_narcoId].consumables[2]),yield)); narcos[_narcoId].cokeTotal+=uint8(yield); narcos[_narcoId].stats[2]+=1; districtsCore.increaseDistrictCoke(district, yield); districtsCore.distributeRevenue.value(refineCost)(uint256(district),50,50); // distribute the revenue to districts pots RefineCokeCompleted(_narcoId, yield); // notification event } function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
/// @title DopeRaider: Collectible, narcos on the Ethereum blockchain. /// @dev The main DopeRaider contract
NatSpecSingleLine
function() external payable { require(msg.sender == address(saleAuction)); }
/// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.)
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 3413, 3508 ] }
54,319
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
DopeRaiderCore
contract DopeRaiderCore is NarcoMinting { // This is the main DopeRaider contract. We have several seperately-instantiated contracts // that handle auctions, districts and the creation of new narcos. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // narco ownership. // // - NarcoBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - NarcoAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - NarcoOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - NarcoUpdates: This file contains the methods necessary to allow a separate contract to update narco stats // // - NarcoAuction: Here we have the public methods for auctioning or bidding on narcos. // The actual auction functionality is handled in a sibling sales contract, // while auction creation and bidding is mostly mediated through this facet of the core contract. // // - NarcoMinting: This final facet contains the functionality we use for creating new gen0 narcos. // We can make up to 4096 "promo" narcos // Set in case the core contract is broken and an upgrade is required address public newContractAddress; bool public gamePaused = true; modifier whenGameNotPaused() { require(!gamePaused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenGamePaused { require(gamePaused); _; } function pause() public onlyCLevel whenGameNotPaused { gamePaused = true; } function unpause() public onlyCLevel whenGamePaused { // can't unpause if contract was upgraded gamePaused = false; } // EVENTS event GrowWeedCompleted(uint256 indexed narcoId, uint yield); event RefineCokeCompleted(uint256 indexed narcoId, uint yield); function DopeRaiderCore() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) public onlyCLevel whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require(msg.sender == address(saleAuction)); } /// @param _id The ID of the narco of interest. function getNarco(uint256 _id) public view returns ( string narcoName, uint256 weedTotal, uint256 cokeTotal, uint16[6] skills, uint8[4] consumables, string genes, uint8 homeLocation, uint16 level, uint256[6] cooldowns, uint256 id, uint16 [9] stats ) { Narco storage narco = narcos[_id]; narcoName = narco.narcoName; weedTotal = narco.weedTotal; cokeTotal = narco.cokeTotal; skills = narco.skills; consumables = narco.consumables; genes = narco.genes; homeLocation = narco.homeLocation; level = getLevel(_id); cooldowns = narco.cooldowns; id = _id; stats = narco.stats; } uint256 public changeIdentityNarcoRespect = 30; function setChangeIdentityNarcoRespect(uint256 _respect) public onlyCLevel { changeIdentityNarcoRespect=_respect; } uint256 public personalisationCost = 0.01 ether; // pimp my narco function setPersonalisationCost(uint256 _cost) public onlyCLevel { personalisationCost=_cost; } function updateNarco(uint256 _narcoId, string _genes, string _name) public payable whenGameNotPaused { require(getLevel(_narcoId)>=changeIdentityNarcoRespect); // minimum level to recruit a narco require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=personalisationCost); narcos[_narcoId].genes = _genes; narcos[_narcoId].narcoName = _name; } uint256 public respectRequiredToRecruit = 150; function setRespectRequiredToRecruit(uint256 _respect) public onlyCLevel { respectRequiredToRecruit=_respect; } function recruitNarco(uint256 _narcoId, string _genes, string _name) public whenGameNotPaused { require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(getLevel(_narcoId)>=respectRequiredToRecruit); // minimum level to recruit a narco require(narcos[_narcoId].stats[8]<getLevel(_narcoId)/respectRequiredToRecruit); // must have recruited < respect / required reqpect (times) _createNarco(_genes,_name, msg.sender); narcos[_narcoId].stats[8]+=1; // increase number recruited } // crafting section uint256 public growCost = 0.003 ether; function setGrowCost(uint256 _cost) public onlyCLevel{ growCost=_cost; } function growWeed(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=growCost); require(now>narcos[_narcoId].cooldowns[1]); //cooldown must have expired uint16 growSkillLevel = narcos[_narcoId].skills[1]; // grow uint16 maxYield = 9 + growSkillLevel; // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[1],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting uint256 cooldown = now + ((910-(10*growSkillLevel))* 1 seconds); //calculate cooldown switch to minutes later narcos[_narcoId].cooldowns[1]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[1]=uint8(subToZero(uint256(narcos[_narcoId].consumables[1]),yield)); narcos[_narcoId].weedTotal+=uint8(yield); narcos[_narcoId].stats[1]+=1; // update the statistic for grow districtsCore.increaseDistrictWeed(district , yield); districtsCore.distributeRevenue.value(growCost)(uint256(district),50,50); // distribute the revenue to districts pots GrowWeedCompleted(_narcoId, yield); // notification event } uint256 public refineCost = 0.003 ether; function setRefineCost(uint256 _cost) public onlyCLevel{ refineCost=_cost; } function refineCoke(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=refineCost); require(now>narcos[_narcoId].cooldowns[2]); //cooldown must have expired uint16 refineSkillLevel = narcos[_narcoId].skills[2]; // refine uint16 maxYield = 3+(refineSkillLevel/3); // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[2],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting // uint256 cooldown = now + min(3 minutes,((168-(2*refineSkillLevel))* 1 seconds)); // calculate cooldown uint256 cooldown = now + ((910-(10*refineSkillLevel))* 1 seconds); // calculate cooldown narcos[_narcoId].cooldowns[2]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[2]=uint8(subToZero(uint256(narcos[_narcoId].consumables[2]),yield)); narcos[_narcoId].cokeTotal+=uint8(yield); narcos[_narcoId].stats[2]+=1; districtsCore.increaseDistrictCoke(district, yield); districtsCore.distributeRevenue.value(refineCost)(uint256(district),50,50); // distribute the revenue to districts pots RefineCokeCompleted(_narcoId, yield); // notification event } function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
/// @title DopeRaider: Collectible, narcos on the Ethereum blockchain. /// @dev The main DopeRaider contract
NatSpecSingleLine
getNarco
function getNarco(uint256 _id) public view returns ( string narcoName, uint256 weedTotal, uint256 cokeTotal, uint16[6] skills, uint8[4] consumables, string genes, uint8 homeLocation, uint16 level, uint256[6] cooldowns, uint256 id, uint16 [9] stats ) { Narco storage narco = narcos[_id]; narcoName = narco.narcoName; weedTotal = narco.weedTotal; cokeTotal = narco.cokeTotal; skills = narco.skills; consumables = narco.consumables; genes = narco.genes; homeLocation = narco.homeLocation; level = getLevel(_id); cooldowns = narco.cooldowns; id = _id; stats = narco.stats; }
/// @param _id The ID of the narco of interest.
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 3566, 4385 ] }
54,320
DopeRaiderCore
DopeRaiderCore.sol
0x3bcbd2093e991363b98cf0f51d40fecd94a55a0d
Solidity
DopeRaiderCore
contract DopeRaiderCore is NarcoMinting { // This is the main DopeRaider contract. We have several seperately-instantiated contracts // that handle auctions, districts and the creation of new narcos. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // narco ownership. // // - NarcoBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - NarcoAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - NarcoOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - NarcoUpdates: This file contains the methods necessary to allow a separate contract to update narco stats // // - NarcoAuction: Here we have the public methods for auctioning or bidding on narcos. // The actual auction functionality is handled in a sibling sales contract, // while auction creation and bidding is mostly mediated through this facet of the core contract. // // - NarcoMinting: This final facet contains the functionality we use for creating new gen0 narcos. // We can make up to 4096 "promo" narcos // Set in case the core contract is broken and an upgrade is required address public newContractAddress; bool public gamePaused = true; modifier whenGameNotPaused() { require(!gamePaused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenGamePaused { require(gamePaused); _; } function pause() public onlyCLevel whenGameNotPaused { gamePaused = true; } function unpause() public onlyCLevel whenGamePaused { // can't unpause if contract was upgraded gamePaused = false; } // EVENTS event GrowWeedCompleted(uint256 indexed narcoId, uint yield); event RefineCokeCompleted(uint256 indexed narcoId, uint yield); function DopeRaiderCore() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) public onlyCLevel whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require(msg.sender == address(saleAuction)); } /// @param _id The ID of the narco of interest. function getNarco(uint256 _id) public view returns ( string narcoName, uint256 weedTotal, uint256 cokeTotal, uint16[6] skills, uint8[4] consumables, string genes, uint8 homeLocation, uint16 level, uint256[6] cooldowns, uint256 id, uint16 [9] stats ) { Narco storage narco = narcos[_id]; narcoName = narco.narcoName; weedTotal = narco.weedTotal; cokeTotal = narco.cokeTotal; skills = narco.skills; consumables = narco.consumables; genes = narco.genes; homeLocation = narco.homeLocation; level = getLevel(_id); cooldowns = narco.cooldowns; id = _id; stats = narco.stats; } uint256 public changeIdentityNarcoRespect = 30; function setChangeIdentityNarcoRespect(uint256 _respect) public onlyCLevel { changeIdentityNarcoRespect=_respect; } uint256 public personalisationCost = 0.01 ether; // pimp my narco function setPersonalisationCost(uint256 _cost) public onlyCLevel { personalisationCost=_cost; } function updateNarco(uint256 _narcoId, string _genes, string _name) public payable whenGameNotPaused { require(getLevel(_narcoId)>=changeIdentityNarcoRespect); // minimum level to recruit a narco require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=personalisationCost); narcos[_narcoId].genes = _genes; narcos[_narcoId].narcoName = _name; } uint256 public respectRequiredToRecruit = 150; function setRespectRequiredToRecruit(uint256 _respect) public onlyCLevel { respectRequiredToRecruit=_respect; } function recruitNarco(uint256 _narcoId, string _genes, string _name) public whenGameNotPaused { require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(getLevel(_narcoId)>=respectRequiredToRecruit); // minimum level to recruit a narco require(narcos[_narcoId].stats[8]<getLevel(_narcoId)/respectRequiredToRecruit); // must have recruited < respect / required reqpect (times) _createNarco(_genes,_name, msg.sender); narcos[_narcoId].stats[8]+=1; // increase number recruited } // crafting section uint256 public growCost = 0.003 ether; function setGrowCost(uint256 _cost) public onlyCLevel{ growCost=_cost; } function growWeed(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=growCost); require(now>narcos[_narcoId].cooldowns[1]); //cooldown must have expired uint16 growSkillLevel = narcos[_narcoId].skills[1]; // grow uint16 maxYield = 9 + growSkillLevel; // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[1],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting uint256 cooldown = now + ((910-(10*growSkillLevel))* 1 seconds); //calculate cooldown switch to minutes later narcos[_narcoId].cooldowns[1]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[1]=uint8(subToZero(uint256(narcos[_narcoId].consumables[1]),yield)); narcos[_narcoId].weedTotal+=uint8(yield); narcos[_narcoId].stats[1]+=1; // update the statistic for grow districtsCore.increaseDistrictWeed(district , yield); districtsCore.distributeRevenue.value(growCost)(uint256(district),50,50); // distribute the revenue to districts pots GrowWeedCompleted(_narcoId, yield); // notification event } uint256 public refineCost = 0.003 ether; function setRefineCost(uint256 _cost) public onlyCLevel{ refineCost=_cost; } function refineCoke(uint256 _narcoId) public payable whenGameNotPaused{ require(msg.sender==narcoIndexToOwner[_narcoId]); // can't be moving other peoples narcos about require(msg.value>=refineCost); require(now>narcos[_narcoId].cooldowns[2]); //cooldown must have expired uint16 refineSkillLevel = narcos[_narcoId].skills[2]; // refine uint16 maxYield = 3+(refineSkillLevel/3); // max amount can be grown based on skill uint yield = min(narcos[_narcoId].consumables[2],maxYield); require(yield>0); // gotta produce something // must be home location uint8 district = districtsCore.getNarcoLocation(_narcoId); require(district==narcos[_narcoId].homeLocation); // do the crafting // uint256 cooldown = now + min(3 minutes,((168-(2*refineSkillLevel))* 1 seconds)); // calculate cooldown uint256 cooldown = now + ((910-(10*refineSkillLevel))* 1 seconds); // calculate cooldown narcos[_narcoId].cooldowns[2]=cooldown; // use all available - for now , maybe later make optional narcos[_narcoId].consumables[2]=uint8(subToZero(uint256(narcos[_narcoId].consumables[2]),yield)); narcos[_narcoId].cokeTotal+=uint8(yield); narcos[_narcoId].stats[2]+=1; districtsCore.increaseDistrictCoke(district, yield); districtsCore.distributeRevenue.value(refineCost)(uint256(district),50,50); // distribute the revenue to districts pots RefineCokeCompleted(_narcoId, yield); // notification event } function min(uint a, uint b) private pure returns (uint) { return a < b ? a : b; } }
/// @title DopeRaider: Collectible, narcos on the Ethereum blockchain. /// @dev The main DopeRaider contract
NatSpecSingleLine
setPersonalisationCost
function setPersonalisationCost(uint256 _cost) public onlyCLevel { personalisationCost=_cost; }
// pimp my narco
LineComment
v0.4.19+commit.c4cbbb05
bzzr://0f28b8959c158eb5414277529fd27a82caedc0f7ffd1730f3ff2ead374e55ac7
{ "func_code_index": [ 4647, 4759 ] }
54,321
TrippedOut
nft test/TrippedOut.sol
0x14c6c10ff89675742707c3a9fa0ee1f42f542e41
Solidity
TrippedOut
contract TrippedOut is Ownable, IERC721Receiver{ using SafeMath for uint256; using Address for address payable; //Burn info address public originalNFTAddress; bool public burnIsActive = false; uint256 public refundAmount; /* * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } constructor( address _originalNFTAddress, uint256 _refundAmount ){ originalNFTAddress = _originalNFTAddress; refundAmount = _refundAmount; } modifier whenPublicBurnActive() { require(burnIsActive, "Public burn is not active"); _; } function togglePublicBurnActive() public onlyOwner { burnIsActive = !burnIsActive; } function setOriginalNFTAddress(address _originalNFTAddress) public onlyOwner { originalNFTAddress = _originalNFTAddress; } function setRefundAmound(uint256 _refundAmount) public onlyOwner { refundAmount = _refundAmount; } function TRIPPEDOUT(uint256[] calldata tokenIds, address payable payee) public whenPublicBurnActive { // send tokens to user if they own them for(uint i = 0; i < tokenIds.length; i++){ require(IERC721(originalNFTAddress).ownerOf(tokenIds[i]) == msg.sender, "Must own NFT to burn."); IERC721(originalNFTAddress).safeTransferFrom(msg.sender, address(this), tokenIds[i]); } payee.sendValue(refundAmount.mul(tokenIds.length)); } function deposit() public payable {} // allow owner to withdraw all funds if needed function withdraw(address payable _to) public onlyOwner { _to.sendValue(address(this).balance); } }
onERC721Received
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; }
/* * Always returns `IERC721Receiver.onERC721Received.selector`. */
Comment
v0.8.0+commit.c7dfd78e
MIT
ipfs://3f78af24c66ae402558611cc18b54295cd616d69399a8819bf107f7883e21c42
{ "func_code_index": [ 324, 487 ] }
54,322
TrippedOut
nft test/TrippedOut.sol
0x14c6c10ff89675742707c3a9fa0ee1f42f542e41
Solidity
TrippedOut
contract TrippedOut is Ownable, IERC721Receiver{ using SafeMath for uint256; using Address for address payable; //Burn info address public originalNFTAddress; bool public burnIsActive = false; uint256 public refundAmount; /* * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } constructor( address _originalNFTAddress, uint256 _refundAmount ){ originalNFTAddress = _originalNFTAddress; refundAmount = _refundAmount; } modifier whenPublicBurnActive() { require(burnIsActive, "Public burn is not active"); _; } function togglePublicBurnActive() public onlyOwner { burnIsActive = !burnIsActive; } function setOriginalNFTAddress(address _originalNFTAddress) public onlyOwner { originalNFTAddress = _originalNFTAddress; } function setRefundAmound(uint256 _refundAmount) public onlyOwner { refundAmount = _refundAmount; } function TRIPPEDOUT(uint256[] calldata tokenIds, address payable payee) public whenPublicBurnActive { // send tokens to user if they own them for(uint i = 0; i < tokenIds.length; i++){ require(IERC721(originalNFTAddress).ownerOf(tokenIds[i]) == msg.sender, "Must own NFT to burn."); IERC721(originalNFTAddress).safeTransferFrom(msg.sender, address(this), tokenIds[i]); } payee.sendValue(refundAmount.mul(tokenIds.length)); } function deposit() public payable {} // allow owner to withdraw all funds if needed function withdraw(address payable _to) public onlyOwner { _to.sendValue(address(this).balance); } }
withdraw
function withdraw(address payable _to) public onlyOwner { _to.sendValue(address(this).balance); }
// allow owner to withdraw all funds if needed
LineComment
v0.8.0+commit.c7dfd78e
MIT
ipfs://3f78af24c66ae402558611cc18b54295cd616d69399a8819bf107f7883e21c42
{ "func_code_index": [ 1690, 1800 ] }
54,323
AaveLinearPool
contracts/LinearPool.sol
0x652d486b80c461c397b0d95612a404da936f3db3
Solidity
LinearPool
abstract contract LinearPool is BasePool, IGeneralPool, IRateProvider { using WordCodec for bytes32; using FixedPoint for uint256; using PriceRateCache for bytes32; using LinearPoolUserData for bytes; uint256 private constant _TOTAL_TOKENS = 3; // Main token, wrapped token, BPT // This is the maximum token amount the Vault can hold. In regular operation, the total BPT supply remains constant // and equal to _INITIAL_BPT_SUPPLY, but most of it remains in the Pool, waiting to be exchanged for tokens. The // actual amount of BPT in circulation is the total supply minus the amount held by the Pool, and is known as the // 'virtual supply'. // The total supply can only change if the emergency pause is activated by governance, enabling an // alternative proportional exit that burns BPT. As this is not expected to happen, we optimize for // success by using _INITIAL_BPT_SUPPLY instead of totalSupply(), saving a storage read. This optimization is only // valid if the Pool is never paused: in case of an emergency that leads to burned tokens, the Pool should not // be used after the buffer period expires and it automatically 'unpauses'. uint256 private constant _INITIAL_BPT_SUPPLY = 2**(112) - 1; IERC20 private immutable _mainToken; IERC20 private immutable _wrappedToken; // The indices of each token when registered, which can then be used to access the balances array. uint256 private immutable _bptIndex; uint256 private immutable _mainIndex; uint256 private immutable _wrappedIndex; // Both BPT and the main token have a regular, constant scaling factor (equal to FixedPoint.ONE for BPT, and // dependent on the number of decimals for the main token). However, the wrapped token's scaling factor has two // components: the usual token decimal scaling factor, and an externally provided rate used to convert wrapped // tokens to an equivalent main token amount. This external rate is expected to be ever increasing, reflecting the // fact that the wrapped token appreciates in value over time (e.g. because it is accruing interest). uint256 private immutable _scalingFactorMainToken; uint256 private immutable _scalingFactorWrappedToken; // The lower and upper target are in BasePool's misc data field, which has 192 bits available (as it shares the same // storage slot as the swap fee percentage, which is 64 bits). These are already scaled by the main token's scaling // factor, which means that the maximum upper target is ~80 billion in the main token units if the token were to // have 18 decimals (2^(192/2) / 10^18), which is more than enough. // [ 64 bits | 96 bits | 96 bits ] // [ reserved | upper target | lower target ] // [ base pool swap fee | misc data ] // [ MSB LSB ] uint256 private constant _LOWER_TARGET_OFFSET = 0; uint256 private constant _UPPER_TARGET_OFFSET = 96; uint256 private constant _MAX_UPPER_TARGET = 2**(96) - 1; event TargetsSet(IERC20 indexed token, uint256 lowerTarget, uint256 upperTarget); constructor( IVault vault, string memory name, string memory symbol, IERC20 mainToken, IERC20 wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, IVault.PoolSpecialization.GENERAL, name, symbol, _sortTokens(mainToken, wrappedToken, this), new address[](_TOTAL_TOKENS), swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // Set tokens _mainToken = mainToken; _wrappedToken = wrappedToken; // Set token indexes (uint256 mainIndex, uint256 wrappedIndex, uint256 bptIndex) = _getSortedTokenIndexes( mainToken, wrappedToken, this ); _bptIndex = bptIndex; _mainIndex = mainIndex; _wrappedIndex = wrappedIndex; // Set scaling factors _scalingFactorMainToken = _computeScalingFactor(mainToken); _scalingFactorWrappedToken = _computeScalingFactor(wrappedToken); // Set initial targets. Lower target must be set to zero because initially there are no fees accumulated. // Otherwise the pool will owe fees at start which results in a manipulable rate. uint256 lowerTarget = 0; _setTargets(mainToken, lowerTarget, upperTarget); } function getMainToken() public view returns (address) { return address(_mainToken); } function getWrappedToken() external view returns (address) { return address(_wrappedToken); } function getBptIndex() external view returns (uint256) { return _bptIndex; } function getMainIndex() external view returns (uint256) { return _mainIndex; } function getWrappedIndex() external view returns (uint256) { return _wrappedIndex; } /** * @dev Finishes initialization of the Linear Pool: it is unusable before calling this function as no BPT will have * been minted. * * Since Linear Pools have preminted BPT stored in the Vault, they require an initial join to deposit said BPT as * their balance. Unfortunately, this cannot be performed during construction, as a join involves calling the * `onJoinPool` function on the Pool, and the Pool will not have any code until construction finishes. Therefore, * this must happen in a separate call. * * It is highly recommended to create Linear pools using the LinearPoolFactory, which calls `initialize` * automatically. */ function initialize() external { bytes32 poolId = getPoolId(); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(poolId); // Joins typically involve the Pool receiving tokens in exchange for newly-minted BPT. In this case however, the // Pool will mint the entire BPT supply to itself, and join itself with it. uint256[] memory maxAmountsIn = new uint256[](_TOTAL_TOKENS); maxAmountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; // The first time this executes, it will call `_onInitializePool` (as the BPT supply will be zero). Future calls // will be routed to `_onJoinPool`, which always reverts, meaning `initialize` will only execute once. IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: _asIAsset(tokens), maxAmountsIn: maxAmountsIn, userData: "", fromInternalBalance: false }); getVault().joinPool(poolId, address(this), address(this), request); } /** * @dev Implementation of onSwap, from IGeneralPool. */ function onSwap( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public view override onlyVault(request.poolId) whenNotPaused returns (uint256) { // In most Pools, swaps involve exchanging one token held by the Pool for another. In this case however, since // one of the three tokens is the BPT itself, a swap might also be a join (main/wrapped for BPT) or an exit // (BPT for main/wrapped). // All three swap types (swaps, joins and exits) are fully disabled if the emergency pause is enabled. Under // these circumstances, the Pool should be exited using the regular Vault.exitPool function. // Sanity check: this is not entirely necessary as the Vault's interface enforces the indices to be valid, but // the check is cheap to perform. _require(indexIn < _TOTAL_TOKENS && indexOut < _TOTAL_TOKENS, Errors.OUT_OF_BOUNDS); // Note that we already know the indices of the main token, wrapped token and BPT, so there is no need to pass // these indices to the inner functions. // Upscale balances by the scaling factors (taking into account the wrapped token rate) uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); if (request.kind == IVault.SwapKind.GIVEN_IN) { // The amount given is for token in, the amount calculated is for token out request.amount = _upscale(request.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(request, balances, params); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } else { // The amount given is for token out, the amount calculated is for token in request.amount = _upscale(request.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(request, balances, params); // amountIn tokens are entering the Pool, so we round up. return _downscaleUp(amountIn, scalingFactors[indexIn]); } } function _onSwapGivenIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenIn == this) { return _swapGivenBptIn(request, balances, params); } else if (request.tokenIn == _mainToken) { return _swapGivenMainIn(request, balances, params); } else if (request.tokenIn == _wrappedToken) { return _swapGivenWrappedIn(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenOut == _mainToken ? LinearMath._calcMainOutPerBptIn : LinearMath._calcWrappedOutPerBptIn)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _wrappedToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerMainIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedOutPerMainIn(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerWrappedIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainOutPerWrappedIn(request.amount, balances[_mainIndex], params); } function _onSwapGivenOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenOut == this) { return _swapGivenBptOut(request, balances, params); } else if (request.tokenOut == _mainToken) { return _swapGivenMainOut(request, balances, params); } else if (request.tokenOut == _wrappedToken) { return _swapGivenWrappedOut(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenIn == _mainToken ? LinearMath._calcMainInPerBptOut : LinearMath._calcWrappedInPerBptOut)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _wrappedToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerMainOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedInPerMainOut(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerWrappedOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainInPerWrappedOut(request.amount, balances[_mainIndex], params); } function _onInitializePool( bytes32, address sender, address recipient, uint256[] memory, bytes memory ) internal view override whenNotPaused returns (uint256, uint256[] memory) { // Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function. _require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION); // The full BPT supply will be minted and deposited in the Pool. Note that there is no need to approve the Vault // as it already has infinite BPT allowance. uint256 bptAmountOut = _INITIAL_BPT_SUPPLY; uint256[] memory amountsIn = new uint256[](_TOTAL_TOKENS); amountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; return (bptAmountOut, amountsIn); } function _onJoinPool( bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory ) internal pure override returns ( uint256, uint256[] memory, uint256[] memory ) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256, uint256[] memory, bytes memory userData ) internal view override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits typically revert, except for the proportional exit when the emergency pause mechanism has been // triggered. This allows for a simple and safe way to exit the Pool. // Note that the rate cache will not be automatically updated in such a scenario (though this can be still done // manually). This however should not lead to any issues as the rate is not important during the emergency exit. // On the contrary, decoupling the rate provider from the emergency exit might be useful under these // circumstances. LinearPoolUserData.ExitKind kind = userData.exitKind(); if (kind != LinearPoolUserData.ExitKind.EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } else { _ensurePaused(); // Note that this will cause the user's BPT to be burned, which is not something that happens during // regular operation of this Pool, and may lead to accounting errors. Because of this, it is highly // advisable to stop using a Pool after it is paused and the pause window expires. (bptAmountIn, amountsOut) = _emergencyProportionalExit(balances, userData); // Due protocol fees are set to zero as this Pool accrues no fees and pays no protocol fees. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } } function _emergencyProportionalExit(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This proportional exit function is only enabled if the contract is paused, to provide users a way to // retrieve their tokens in case of an emergency. // // This particular exit function is the only one available because it is the simplest, and therefore least // likely to be incorrect, or revert and lock funds. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. // This process burns BPT, rendering `_getApproximateVirtualSupply` inaccurate, so we use the real method here uint256[] memory amountsOut = LinearMath._calcTokensOutGivenExactBptIn( balances, bptAmountIn, _getVirtualSupply(balances[_bptIndex]), _bptIndex ); return (bptAmountIn, amountsOut); } function _getMaxTokens() internal pure override returns (uint256) { return _TOTAL_TOKENS; } function _getMinimumBpt() internal pure override returns (uint256) { // Linear Pools don't lock any BPT, as the total supply will already be forever non-zero due to the preminting // mechanism, ensuring initialization only occurs once. return 0; } function _getTotalTokens() internal view virtual override returns (uint256) { return _TOTAL_TOKENS; } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { if (token == _mainToken) { return _scalingFactorMainToken; } else if (token == _wrappedToken) { // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token // increases in value. return _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); } else if (token == this) { return FixedPoint.ONE; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS); // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in // value. scalingFactors[_mainIndex] = _scalingFactorMainToken; scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); scalingFactors[_bptIndex] = FixedPoint.ONE; return scalingFactors; } // Price rates /** * @dev For a Linear Pool, the rate represents the appreciation of BPT with respect to the underlying tokens. This * rate increases slowly as the wrapped token appreciates in value. */ function getRate() external view override returns (uint256) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); _upscaleArray(balances, _scalingFactors()); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); uint256 totalBalance = LinearMath._calcInvariant( LinearMath._toNominal(balances[_mainIndex], params), balances[_wrappedIndex] ); // Note that we're dividing by the virtual supply, which may be zero (causing this call to revert). However, the // only way for that to happen would be for all LPs to exit the Pool, and nothing prevents new LPs from // joining it later on. return totalBalance.divUp(_getApproximateVirtualSupply(balances[_bptIndex])); } function getWrappedTokenRate() external view returns (uint256) { return _getWrappedTokenRate(); } function _getWrappedTokenRate() internal view virtual returns (uint256); function getTargets() public view returns (uint256 lowerTarget, uint256 upperTarget) { bytes32 miscData = _getMiscData(); lowerTarget = miscData.decodeUint96(_LOWER_TARGET_OFFSET); upperTarget = miscData.decodeUint96(_UPPER_TARGET_OFFSET); } function _setTargets( IERC20 mainToken, uint256 lowerTarget, uint256 upperTarget ) private { _require(lowerTarget <= upperTarget, Errors.LOWER_GREATER_THAN_UPPER_TARGET); _require(upperTarget <= _MAX_UPPER_TARGET, Errors.UPPER_TARGET_TOO_HIGH); // Pack targets as two uint96 values into a single storage slot. This results in targets being capped to 96 // bits, but that should be more than enough. _setMiscData( WordCodec.encodeUint(lowerTarget, _LOWER_TARGET_OFFSET) | WordCodec.encodeUint(upperTarget, _UPPER_TARGET_OFFSET) ); emit TargetsSet(mainToken, lowerTarget, upperTarget); } function setTargets(uint256 newLowerTarget, uint256 newUpperTarget) external authenticate { // For a new target range to be valid: // - the pool must currently be between the current targets (meaning no fees are currently pending) // - the pool must currently be between the new targets (meaning setting them does not cause for fees to be // pending) // // The first requirement could be relaxed, as the LPs actually benefit from the pending fees not being paid out, // but being stricter makes analysis easier at little expense. (uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE); _require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE); _setTargets(_mainToken, newLowerTarget, newUpperTarget); } function setSwapFeePercentage(uint256 swapFeePercentage) public override { // For the swap fee percentage to be changeable: // - the pool must currently be between the current targets (meaning no fees are currently pending) // // As the amount of accrued fees is not explicitly stored but rather derived from the main token balance and the // current swap fee percentage, requiring for no fees to be pending prevents the fee setter from changing the // amount of pending fees, which they could use to e.g. drain Pool funds in the form of inflated fees. (uint256 lowerTarget, uint256 upperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(lowerTarget, upperTarget), Errors.OUT_OF_TARGET_RANGE); super.setSwapFeePercentage(swapFeePercentage); } function _isMainBalanceWithinTargets(uint256 lowerTarget, uint256 upperTarget) private view returns (bool) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); uint256 mainTokenBalance = _upscale(balances[_mainIndex], _scalingFactor(_mainToken)); return mainTokenBalance >= lowerTarget && mainTokenBalance <= upperTarget; } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return actionId == getActionId(this.setTargets.selector) || super._isOwnerOnlyAction(actionId); } /** * @dev Returns the number of tokens in circulation. * * In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` * remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it. */ function getVirtualSupply() external view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has // 18 decimals), but we do it for completeness. uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this)); return _getVirtualSupply(bptBalance); } function _getVirtualSupply(uint256 bptBalance) internal view returns (uint256) { return totalSupply().sub(bptBalance); } /** * @dev Computes an approximation of virtual supply, which costs less gas than `_getVirtualSupply` and returns the * same value in all cases except when the emergency pause has been enabled and BPT burned as part of the emergency * exit process. */ function _getApproximateVirtualSupply(uint256 bptBalance) internal pure returns (uint256) { // No need for checked arithmetic as _INITIAL_BPT_SUPPLY is always greater than any valid Vault BPT balance. return _INITIAL_BPT_SUPPLY - bptBalance; } }
/** * @dev Linear Pools are designed to hold two assets: "main" and "wrapped" tokens that have an equal value underlying * token (e.g., DAI and waDAI). There must be an external feed available to provide an exact, non-manipulable exchange * rate between the tokens. In particular, any reversible manipulation (e.g. causing the rate to increase and then * decrease) can lead to severe issues and loss of funds. * * The Pool will register three tokens in the Vault however: the two assets and the BPT itself, * so that BPT can be exchanged (effectively joining and exiting) via swaps. * * Despite inheriting from BasePool, much of the basic behavior changes. This Pool does not support regular joins and * exits, as the entire BPT supply is 'preminted' during initialization. * * Unlike most other Pools, this one does not attempt to create revenue by charging fees: value is derived by holding * the wrapped, yield-bearing asset. However, the 'swap fee percentage' value is still used, albeit with a different * meaning. This Pool attempts to hold a certain amount of "main" tokens, between a lower and upper target value. * The pool charges fees on trades that move the balance outside that range, which are then paid back as incentives to * traders whose swaps return the balance to the desired region. * The net revenue via fees is expected to be zero: all collected fees are used to pay for this 'rebalancing'. */
NatSpecMultiLine
initialize
function initialize() external { bytes32 poolId = getPoolId(); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(poolId); // Joins typically involve the Pool receiving tokens in exchange for newly-minted BPT. In this case however, the // Pool will mint the entire BPT supply to itself, and join itself with it. uint256[] memory maxAmountsIn = new uint256[](_TOTAL_TOKENS); maxAmountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; // The first time this executes, it will call `_onInitializePool` (as the BPT supply will be zero). Future calls // will be routed to `_onJoinPool`, which always reverts, meaning `initialize` will only execute once. IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: _asIAsset(tokens), maxAmountsIn: maxAmountsIn, userData: "", fromInternalBalance: false }); getVault().joinPool(poolId, address(this), address(this), request); }
/** * @dev Finishes initialization of the Linear Pool: it is unusable before calling this function as no BPT will have * been minted. * * Since Linear Pools have preminted BPT stored in the Vault, they require an initial join to deposit said BPT as * their balance. Unfortunately, this cannot be performed during construction, as a join involves calling the * `onJoinPool` function on the Pool, and the Pool will not have any code until construction finishes. Therefore, * this must happen in a separate call. * * It is highly recommended to create Linear pools using the LinearPoolFactory, which calls `initialize` * automatically. */
NatSpecMultiLine
v0.7.1+commit.f4a555be
{ "func_code_index": [ 5956, 6979 ] }
54,324
AaveLinearPool
contracts/LinearPool.sol
0x652d486b80c461c397b0d95612a404da936f3db3
Solidity
LinearPool
abstract contract LinearPool is BasePool, IGeneralPool, IRateProvider { using WordCodec for bytes32; using FixedPoint for uint256; using PriceRateCache for bytes32; using LinearPoolUserData for bytes; uint256 private constant _TOTAL_TOKENS = 3; // Main token, wrapped token, BPT // This is the maximum token amount the Vault can hold. In regular operation, the total BPT supply remains constant // and equal to _INITIAL_BPT_SUPPLY, but most of it remains in the Pool, waiting to be exchanged for tokens. The // actual amount of BPT in circulation is the total supply minus the amount held by the Pool, and is known as the // 'virtual supply'. // The total supply can only change if the emergency pause is activated by governance, enabling an // alternative proportional exit that burns BPT. As this is not expected to happen, we optimize for // success by using _INITIAL_BPT_SUPPLY instead of totalSupply(), saving a storage read. This optimization is only // valid if the Pool is never paused: in case of an emergency that leads to burned tokens, the Pool should not // be used after the buffer period expires and it automatically 'unpauses'. uint256 private constant _INITIAL_BPT_SUPPLY = 2**(112) - 1; IERC20 private immutable _mainToken; IERC20 private immutable _wrappedToken; // The indices of each token when registered, which can then be used to access the balances array. uint256 private immutable _bptIndex; uint256 private immutable _mainIndex; uint256 private immutable _wrappedIndex; // Both BPT and the main token have a regular, constant scaling factor (equal to FixedPoint.ONE for BPT, and // dependent on the number of decimals for the main token). However, the wrapped token's scaling factor has two // components: the usual token decimal scaling factor, and an externally provided rate used to convert wrapped // tokens to an equivalent main token amount. This external rate is expected to be ever increasing, reflecting the // fact that the wrapped token appreciates in value over time (e.g. because it is accruing interest). uint256 private immutable _scalingFactorMainToken; uint256 private immutable _scalingFactorWrappedToken; // The lower and upper target are in BasePool's misc data field, which has 192 bits available (as it shares the same // storage slot as the swap fee percentage, which is 64 bits). These are already scaled by the main token's scaling // factor, which means that the maximum upper target is ~80 billion in the main token units if the token were to // have 18 decimals (2^(192/2) / 10^18), which is more than enough. // [ 64 bits | 96 bits | 96 bits ] // [ reserved | upper target | lower target ] // [ base pool swap fee | misc data ] // [ MSB LSB ] uint256 private constant _LOWER_TARGET_OFFSET = 0; uint256 private constant _UPPER_TARGET_OFFSET = 96; uint256 private constant _MAX_UPPER_TARGET = 2**(96) - 1; event TargetsSet(IERC20 indexed token, uint256 lowerTarget, uint256 upperTarget); constructor( IVault vault, string memory name, string memory symbol, IERC20 mainToken, IERC20 wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, IVault.PoolSpecialization.GENERAL, name, symbol, _sortTokens(mainToken, wrappedToken, this), new address[](_TOTAL_TOKENS), swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // Set tokens _mainToken = mainToken; _wrappedToken = wrappedToken; // Set token indexes (uint256 mainIndex, uint256 wrappedIndex, uint256 bptIndex) = _getSortedTokenIndexes( mainToken, wrappedToken, this ); _bptIndex = bptIndex; _mainIndex = mainIndex; _wrappedIndex = wrappedIndex; // Set scaling factors _scalingFactorMainToken = _computeScalingFactor(mainToken); _scalingFactorWrappedToken = _computeScalingFactor(wrappedToken); // Set initial targets. Lower target must be set to zero because initially there are no fees accumulated. // Otherwise the pool will owe fees at start which results in a manipulable rate. uint256 lowerTarget = 0; _setTargets(mainToken, lowerTarget, upperTarget); } function getMainToken() public view returns (address) { return address(_mainToken); } function getWrappedToken() external view returns (address) { return address(_wrappedToken); } function getBptIndex() external view returns (uint256) { return _bptIndex; } function getMainIndex() external view returns (uint256) { return _mainIndex; } function getWrappedIndex() external view returns (uint256) { return _wrappedIndex; } /** * @dev Finishes initialization of the Linear Pool: it is unusable before calling this function as no BPT will have * been minted. * * Since Linear Pools have preminted BPT stored in the Vault, they require an initial join to deposit said BPT as * their balance. Unfortunately, this cannot be performed during construction, as a join involves calling the * `onJoinPool` function on the Pool, and the Pool will not have any code until construction finishes. Therefore, * this must happen in a separate call. * * It is highly recommended to create Linear pools using the LinearPoolFactory, which calls `initialize` * automatically. */ function initialize() external { bytes32 poolId = getPoolId(); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(poolId); // Joins typically involve the Pool receiving tokens in exchange for newly-minted BPT. In this case however, the // Pool will mint the entire BPT supply to itself, and join itself with it. uint256[] memory maxAmountsIn = new uint256[](_TOTAL_TOKENS); maxAmountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; // The first time this executes, it will call `_onInitializePool` (as the BPT supply will be zero). Future calls // will be routed to `_onJoinPool`, which always reverts, meaning `initialize` will only execute once. IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: _asIAsset(tokens), maxAmountsIn: maxAmountsIn, userData: "", fromInternalBalance: false }); getVault().joinPool(poolId, address(this), address(this), request); } /** * @dev Implementation of onSwap, from IGeneralPool. */ function onSwap( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public view override onlyVault(request.poolId) whenNotPaused returns (uint256) { // In most Pools, swaps involve exchanging one token held by the Pool for another. In this case however, since // one of the three tokens is the BPT itself, a swap might also be a join (main/wrapped for BPT) or an exit // (BPT for main/wrapped). // All three swap types (swaps, joins and exits) are fully disabled if the emergency pause is enabled. Under // these circumstances, the Pool should be exited using the regular Vault.exitPool function. // Sanity check: this is not entirely necessary as the Vault's interface enforces the indices to be valid, but // the check is cheap to perform. _require(indexIn < _TOTAL_TOKENS && indexOut < _TOTAL_TOKENS, Errors.OUT_OF_BOUNDS); // Note that we already know the indices of the main token, wrapped token and BPT, so there is no need to pass // these indices to the inner functions. // Upscale balances by the scaling factors (taking into account the wrapped token rate) uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); if (request.kind == IVault.SwapKind.GIVEN_IN) { // The amount given is for token in, the amount calculated is for token out request.amount = _upscale(request.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(request, balances, params); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } else { // The amount given is for token out, the amount calculated is for token in request.amount = _upscale(request.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(request, balances, params); // amountIn tokens are entering the Pool, so we round up. return _downscaleUp(amountIn, scalingFactors[indexIn]); } } function _onSwapGivenIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenIn == this) { return _swapGivenBptIn(request, balances, params); } else if (request.tokenIn == _mainToken) { return _swapGivenMainIn(request, balances, params); } else if (request.tokenIn == _wrappedToken) { return _swapGivenWrappedIn(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenOut == _mainToken ? LinearMath._calcMainOutPerBptIn : LinearMath._calcWrappedOutPerBptIn)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _wrappedToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerMainIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedOutPerMainIn(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerWrappedIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainOutPerWrappedIn(request.amount, balances[_mainIndex], params); } function _onSwapGivenOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenOut == this) { return _swapGivenBptOut(request, balances, params); } else if (request.tokenOut == _mainToken) { return _swapGivenMainOut(request, balances, params); } else if (request.tokenOut == _wrappedToken) { return _swapGivenWrappedOut(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenIn == _mainToken ? LinearMath._calcMainInPerBptOut : LinearMath._calcWrappedInPerBptOut)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _wrappedToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerMainOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedInPerMainOut(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerWrappedOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainInPerWrappedOut(request.amount, balances[_mainIndex], params); } function _onInitializePool( bytes32, address sender, address recipient, uint256[] memory, bytes memory ) internal view override whenNotPaused returns (uint256, uint256[] memory) { // Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function. _require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION); // The full BPT supply will be minted and deposited in the Pool. Note that there is no need to approve the Vault // as it already has infinite BPT allowance. uint256 bptAmountOut = _INITIAL_BPT_SUPPLY; uint256[] memory amountsIn = new uint256[](_TOTAL_TOKENS); amountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; return (bptAmountOut, amountsIn); } function _onJoinPool( bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory ) internal pure override returns ( uint256, uint256[] memory, uint256[] memory ) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256, uint256[] memory, bytes memory userData ) internal view override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits typically revert, except for the proportional exit when the emergency pause mechanism has been // triggered. This allows for a simple and safe way to exit the Pool. // Note that the rate cache will not be automatically updated in such a scenario (though this can be still done // manually). This however should not lead to any issues as the rate is not important during the emergency exit. // On the contrary, decoupling the rate provider from the emergency exit might be useful under these // circumstances. LinearPoolUserData.ExitKind kind = userData.exitKind(); if (kind != LinearPoolUserData.ExitKind.EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } else { _ensurePaused(); // Note that this will cause the user's BPT to be burned, which is not something that happens during // regular operation of this Pool, and may lead to accounting errors. Because of this, it is highly // advisable to stop using a Pool after it is paused and the pause window expires. (bptAmountIn, amountsOut) = _emergencyProportionalExit(balances, userData); // Due protocol fees are set to zero as this Pool accrues no fees and pays no protocol fees. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } } function _emergencyProportionalExit(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This proportional exit function is only enabled if the contract is paused, to provide users a way to // retrieve their tokens in case of an emergency. // // This particular exit function is the only one available because it is the simplest, and therefore least // likely to be incorrect, or revert and lock funds. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. // This process burns BPT, rendering `_getApproximateVirtualSupply` inaccurate, so we use the real method here uint256[] memory amountsOut = LinearMath._calcTokensOutGivenExactBptIn( balances, bptAmountIn, _getVirtualSupply(balances[_bptIndex]), _bptIndex ); return (bptAmountIn, amountsOut); } function _getMaxTokens() internal pure override returns (uint256) { return _TOTAL_TOKENS; } function _getMinimumBpt() internal pure override returns (uint256) { // Linear Pools don't lock any BPT, as the total supply will already be forever non-zero due to the preminting // mechanism, ensuring initialization only occurs once. return 0; } function _getTotalTokens() internal view virtual override returns (uint256) { return _TOTAL_TOKENS; } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { if (token == _mainToken) { return _scalingFactorMainToken; } else if (token == _wrappedToken) { // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token // increases in value. return _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); } else if (token == this) { return FixedPoint.ONE; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS); // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in // value. scalingFactors[_mainIndex] = _scalingFactorMainToken; scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); scalingFactors[_bptIndex] = FixedPoint.ONE; return scalingFactors; } // Price rates /** * @dev For a Linear Pool, the rate represents the appreciation of BPT with respect to the underlying tokens. This * rate increases slowly as the wrapped token appreciates in value. */ function getRate() external view override returns (uint256) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); _upscaleArray(balances, _scalingFactors()); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); uint256 totalBalance = LinearMath._calcInvariant( LinearMath._toNominal(balances[_mainIndex], params), balances[_wrappedIndex] ); // Note that we're dividing by the virtual supply, which may be zero (causing this call to revert). However, the // only way for that to happen would be for all LPs to exit the Pool, and nothing prevents new LPs from // joining it later on. return totalBalance.divUp(_getApproximateVirtualSupply(balances[_bptIndex])); } function getWrappedTokenRate() external view returns (uint256) { return _getWrappedTokenRate(); } function _getWrappedTokenRate() internal view virtual returns (uint256); function getTargets() public view returns (uint256 lowerTarget, uint256 upperTarget) { bytes32 miscData = _getMiscData(); lowerTarget = miscData.decodeUint96(_LOWER_TARGET_OFFSET); upperTarget = miscData.decodeUint96(_UPPER_TARGET_OFFSET); } function _setTargets( IERC20 mainToken, uint256 lowerTarget, uint256 upperTarget ) private { _require(lowerTarget <= upperTarget, Errors.LOWER_GREATER_THAN_UPPER_TARGET); _require(upperTarget <= _MAX_UPPER_TARGET, Errors.UPPER_TARGET_TOO_HIGH); // Pack targets as two uint96 values into a single storage slot. This results in targets being capped to 96 // bits, but that should be more than enough. _setMiscData( WordCodec.encodeUint(lowerTarget, _LOWER_TARGET_OFFSET) | WordCodec.encodeUint(upperTarget, _UPPER_TARGET_OFFSET) ); emit TargetsSet(mainToken, lowerTarget, upperTarget); } function setTargets(uint256 newLowerTarget, uint256 newUpperTarget) external authenticate { // For a new target range to be valid: // - the pool must currently be between the current targets (meaning no fees are currently pending) // - the pool must currently be between the new targets (meaning setting them does not cause for fees to be // pending) // // The first requirement could be relaxed, as the LPs actually benefit from the pending fees not being paid out, // but being stricter makes analysis easier at little expense. (uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE); _require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE); _setTargets(_mainToken, newLowerTarget, newUpperTarget); } function setSwapFeePercentage(uint256 swapFeePercentage) public override { // For the swap fee percentage to be changeable: // - the pool must currently be between the current targets (meaning no fees are currently pending) // // As the amount of accrued fees is not explicitly stored but rather derived from the main token balance and the // current swap fee percentage, requiring for no fees to be pending prevents the fee setter from changing the // amount of pending fees, which they could use to e.g. drain Pool funds in the form of inflated fees. (uint256 lowerTarget, uint256 upperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(lowerTarget, upperTarget), Errors.OUT_OF_TARGET_RANGE); super.setSwapFeePercentage(swapFeePercentage); } function _isMainBalanceWithinTargets(uint256 lowerTarget, uint256 upperTarget) private view returns (bool) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); uint256 mainTokenBalance = _upscale(balances[_mainIndex], _scalingFactor(_mainToken)); return mainTokenBalance >= lowerTarget && mainTokenBalance <= upperTarget; } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return actionId == getActionId(this.setTargets.selector) || super._isOwnerOnlyAction(actionId); } /** * @dev Returns the number of tokens in circulation. * * In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` * remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it. */ function getVirtualSupply() external view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has // 18 decimals), but we do it for completeness. uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this)); return _getVirtualSupply(bptBalance); } function _getVirtualSupply(uint256 bptBalance) internal view returns (uint256) { return totalSupply().sub(bptBalance); } /** * @dev Computes an approximation of virtual supply, which costs less gas than `_getVirtualSupply` and returns the * same value in all cases except when the emergency pause has been enabled and BPT burned as part of the emergency * exit process. */ function _getApproximateVirtualSupply(uint256 bptBalance) internal pure returns (uint256) { // No need for checked arithmetic as _INITIAL_BPT_SUPPLY is always greater than any valid Vault BPT balance. return _INITIAL_BPT_SUPPLY - bptBalance; } }
/** * @dev Linear Pools are designed to hold two assets: "main" and "wrapped" tokens that have an equal value underlying * token (e.g., DAI and waDAI). There must be an external feed available to provide an exact, non-manipulable exchange * rate between the tokens. In particular, any reversible manipulation (e.g. causing the rate to increase and then * decrease) can lead to severe issues and loss of funds. * * The Pool will register three tokens in the Vault however: the two assets and the BPT itself, * so that BPT can be exchanged (effectively joining and exiting) via swaps. * * Despite inheriting from BasePool, much of the basic behavior changes. This Pool does not support regular joins and * exits, as the entire BPT supply is 'preminted' during initialization. * * Unlike most other Pools, this one does not attempt to create revenue by charging fees: value is derived by holding * the wrapped, yield-bearing asset. However, the 'swap fee percentage' value is still used, albeit with a different * meaning. This Pool attempts to hold a certain amount of "main" tokens, between a lower and upper target value. * The pool charges fees on trades that move the balance outside that range, which are then paid back as incentives to * traders whose swaps return the balance to the desired region. * The net revenue via fees is expected to be zero: all collected fees are used to pay for this 'rebalancing'. */
NatSpecMultiLine
onSwap
function onSwap( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public view override onlyVault(request.poolId) whenNotPaused returns (uint256) { // In most Pools, swaps involve exchanging one token held by the Pool for another. In this case however, since // one of the three tokens is the BPT itself, a swap might also be a join (main/wrapped for BPT) or an exit // (BPT for main/wrapped). // All three swap types (swaps, joins and exits) are fully disabled if the emergency pause is enabled. Under // these circumstances, the Pool should be exited using the regular Vault.exitPool function. // Sanity check: this is not entirely necessary as the Vault's interface enforces the indices to be valid, but // the check is cheap to perform. _require(indexIn < _TOTAL_TOKENS && indexOut < _TOTAL_TOKENS, Errors.OUT_OF_BOUNDS); // Note that we already know the indices of the main token, wrapped token and BPT, so there is no need to pass // these indices to the inner functions. // Upscale balances by the scaling factors (taking into account the wrapped token rate) uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); if (request.kind == IVault.SwapKind.GIVEN_IN) { // The amount given is for token in, the amount calculated is for token out request.amount = _upscale(request.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(request, balances, params); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } else { // The amount given is for token out, the amount calculated is for token in request.amount = _upscale(request.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(request, balances, params); // amountIn tokens are entering the Pool, so we round up. return _downscaleUp(amountIn, scalingFactors[indexIn]); } }
/** * @dev Implementation of onSwap, from IGeneralPool. */
NatSpecMultiLine
v0.7.1+commit.f4a555be
{ "func_code_index": [ 7054, 9520 ] }
54,325
AaveLinearPool
contracts/LinearPool.sol
0x652d486b80c461c397b0d95612a404da936f3db3
Solidity
LinearPool
abstract contract LinearPool is BasePool, IGeneralPool, IRateProvider { using WordCodec for bytes32; using FixedPoint for uint256; using PriceRateCache for bytes32; using LinearPoolUserData for bytes; uint256 private constant _TOTAL_TOKENS = 3; // Main token, wrapped token, BPT // This is the maximum token amount the Vault can hold. In regular operation, the total BPT supply remains constant // and equal to _INITIAL_BPT_SUPPLY, but most of it remains in the Pool, waiting to be exchanged for tokens. The // actual amount of BPT in circulation is the total supply minus the amount held by the Pool, and is known as the // 'virtual supply'. // The total supply can only change if the emergency pause is activated by governance, enabling an // alternative proportional exit that burns BPT. As this is not expected to happen, we optimize for // success by using _INITIAL_BPT_SUPPLY instead of totalSupply(), saving a storage read. This optimization is only // valid if the Pool is never paused: in case of an emergency that leads to burned tokens, the Pool should not // be used after the buffer period expires and it automatically 'unpauses'. uint256 private constant _INITIAL_BPT_SUPPLY = 2**(112) - 1; IERC20 private immutable _mainToken; IERC20 private immutable _wrappedToken; // The indices of each token when registered, which can then be used to access the balances array. uint256 private immutable _bptIndex; uint256 private immutable _mainIndex; uint256 private immutable _wrappedIndex; // Both BPT and the main token have a regular, constant scaling factor (equal to FixedPoint.ONE for BPT, and // dependent on the number of decimals for the main token). However, the wrapped token's scaling factor has two // components: the usual token decimal scaling factor, and an externally provided rate used to convert wrapped // tokens to an equivalent main token amount. This external rate is expected to be ever increasing, reflecting the // fact that the wrapped token appreciates in value over time (e.g. because it is accruing interest). uint256 private immutable _scalingFactorMainToken; uint256 private immutable _scalingFactorWrappedToken; // The lower and upper target are in BasePool's misc data field, which has 192 bits available (as it shares the same // storage slot as the swap fee percentage, which is 64 bits). These are already scaled by the main token's scaling // factor, which means that the maximum upper target is ~80 billion in the main token units if the token were to // have 18 decimals (2^(192/2) / 10^18), which is more than enough. // [ 64 bits | 96 bits | 96 bits ] // [ reserved | upper target | lower target ] // [ base pool swap fee | misc data ] // [ MSB LSB ] uint256 private constant _LOWER_TARGET_OFFSET = 0; uint256 private constant _UPPER_TARGET_OFFSET = 96; uint256 private constant _MAX_UPPER_TARGET = 2**(96) - 1; event TargetsSet(IERC20 indexed token, uint256 lowerTarget, uint256 upperTarget); constructor( IVault vault, string memory name, string memory symbol, IERC20 mainToken, IERC20 wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, IVault.PoolSpecialization.GENERAL, name, symbol, _sortTokens(mainToken, wrappedToken, this), new address[](_TOTAL_TOKENS), swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // Set tokens _mainToken = mainToken; _wrappedToken = wrappedToken; // Set token indexes (uint256 mainIndex, uint256 wrappedIndex, uint256 bptIndex) = _getSortedTokenIndexes( mainToken, wrappedToken, this ); _bptIndex = bptIndex; _mainIndex = mainIndex; _wrappedIndex = wrappedIndex; // Set scaling factors _scalingFactorMainToken = _computeScalingFactor(mainToken); _scalingFactorWrappedToken = _computeScalingFactor(wrappedToken); // Set initial targets. Lower target must be set to zero because initially there are no fees accumulated. // Otherwise the pool will owe fees at start which results in a manipulable rate. uint256 lowerTarget = 0; _setTargets(mainToken, lowerTarget, upperTarget); } function getMainToken() public view returns (address) { return address(_mainToken); } function getWrappedToken() external view returns (address) { return address(_wrappedToken); } function getBptIndex() external view returns (uint256) { return _bptIndex; } function getMainIndex() external view returns (uint256) { return _mainIndex; } function getWrappedIndex() external view returns (uint256) { return _wrappedIndex; } /** * @dev Finishes initialization of the Linear Pool: it is unusable before calling this function as no BPT will have * been minted. * * Since Linear Pools have preminted BPT stored in the Vault, they require an initial join to deposit said BPT as * their balance. Unfortunately, this cannot be performed during construction, as a join involves calling the * `onJoinPool` function on the Pool, and the Pool will not have any code until construction finishes. Therefore, * this must happen in a separate call. * * It is highly recommended to create Linear pools using the LinearPoolFactory, which calls `initialize` * automatically. */ function initialize() external { bytes32 poolId = getPoolId(); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(poolId); // Joins typically involve the Pool receiving tokens in exchange for newly-minted BPT. In this case however, the // Pool will mint the entire BPT supply to itself, and join itself with it. uint256[] memory maxAmountsIn = new uint256[](_TOTAL_TOKENS); maxAmountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; // The first time this executes, it will call `_onInitializePool` (as the BPT supply will be zero). Future calls // will be routed to `_onJoinPool`, which always reverts, meaning `initialize` will only execute once. IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: _asIAsset(tokens), maxAmountsIn: maxAmountsIn, userData: "", fromInternalBalance: false }); getVault().joinPool(poolId, address(this), address(this), request); } /** * @dev Implementation of onSwap, from IGeneralPool. */ function onSwap( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public view override onlyVault(request.poolId) whenNotPaused returns (uint256) { // In most Pools, swaps involve exchanging one token held by the Pool for another. In this case however, since // one of the three tokens is the BPT itself, a swap might also be a join (main/wrapped for BPT) or an exit // (BPT for main/wrapped). // All three swap types (swaps, joins and exits) are fully disabled if the emergency pause is enabled. Under // these circumstances, the Pool should be exited using the regular Vault.exitPool function. // Sanity check: this is not entirely necessary as the Vault's interface enforces the indices to be valid, but // the check is cheap to perform. _require(indexIn < _TOTAL_TOKENS && indexOut < _TOTAL_TOKENS, Errors.OUT_OF_BOUNDS); // Note that we already know the indices of the main token, wrapped token and BPT, so there is no need to pass // these indices to the inner functions. // Upscale balances by the scaling factors (taking into account the wrapped token rate) uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); if (request.kind == IVault.SwapKind.GIVEN_IN) { // The amount given is for token in, the amount calculated is for token out request.amount = _upscale(request.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(request, balances, params); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } else { // The amount given is for token out, the amount calculated is for token in request.amount = _upscale(request.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(request, balances, params); // amountIn tokens are entering the Pool, so we round up. return _downscaleUp(amountIn, scalingFactors[indexIn]); } } function _onSwapGivenIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenIn == this) { return _swapGivenBptIn(request, balances, params); } else if (request.tokenIn == _mainToken) { return _swapGivenMainIn(request, balances, params); } else if (request.tokenIn == _wrappedToken) { return _swapGivenWrappedIn(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenOut == _mainToken ? LinearMath._calcMainOutPerBptIn : LinearMath._calcWrappedOutPerBptIn)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _wrappedToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerMainIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedOutPerMainIn(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerWrappedIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainOutPerWrappedIn(request.amount, balances[_mainIndex], params); } function _onSwapGivenOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenOut == this) { return _swapGivenBptOut(request, balances, params); } else if (request.tokenOut == _mainToken) { return _swapGivenMainOut(request, balances, params); } else if (request.tokenOut == _wrappedToken) { return _swapGivenWrappedOut(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenIn == _mainToken ? LinearMath._calcMainInPerBptOut : LinearMath._calcWrappedInPerBptOut)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _wrappedToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerMainOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedInPerMainOut(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerWrappedOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainInPerWrappedOut(request.amount, balances[_mainIndex], params); } function _onInitializePool( bytes32, address sender, address recipient, uint256[] memory, bytes memory ) internal view override whenNotPaused returns (uint256, uint256[] memory) { // Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function. _require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION); // The full BPT supply will be minted and deposited in the Pool. Note that there is no need to approve the Vault // as it already has infinite BPT allowance. uint256 bptAmountOut = _INITIAL_BPT_SUPPLY; uint256[] memory amountsIn = new uint256[](_TOTAL_TOKENS); amountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; return (bptAmountOut, amountsIn); } function _onJoinPool( bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory ) internal pure override returns ( uint256, uint256[] memory, uint256[] memory ) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256, uint256[] memory, bytes memory userData ) internal view override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits typically revert, except for the proportional exit when the emergency pause mechanism has been // triggered. This allows for a simple and safe way to exit the Pool. // Note that the rate cache will not be automatically updated in such a scenario (though this can be still done // manually). This however should not lead to any issues as the rate is not important during the emergency exit. // On the contrary, decoupling the rate provider from the emergency exit might be useful under these // circumstances. LinearPoolUserData.ExitKind kind = userData.exitKind(); if (kind != LinearPoolUserData.ExitKind.EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } else { _ensurePaused(); // Note that this will cause the user's BPT to be burned, which is not something that happens during // regular operation of this Pool, and may lead to accounting errors. Because of this, it is highly // advisable to stop using a Pool after it is paused and the pause window expires. (bptAmountIn, amountsOut) = _emergencyProportionalExit(balances, userData); // Due protocol fees are set to zero as this Pool accrues no fees and pays no protocol fees. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } } function _emergencyProportionalExit(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This proportional exit function is only enabled if the contract is paused, to provide users a way to // retrieve their tokens in case of an emergency. // // This particular exit function is the only one available because it is the simplest, and therefore least // likely to be incorrect, or revert and lock funds. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. // This process burns BPT, rendering `_getApproximateVirtualSupply` inaccurate, so we use the real method here uint256[] memory amountsOut = LinearMath._calcTokensOutGivenExactBptIn( balances, bptAmountIn, _getVirtualSupply(balances[_bptIndex]), _bptIndex ); return (bptAmountIn, amountsOut); } function _getMaxTokens() internal pure override returns (uint256) { return _TOTAL_TOKENS; } function _getMinimumBpt() internal pure override returns (uint256) { // Linear Pools don't lock any BPT, as the total supply will already be forever non-zero due to the preminting // mechanism, ensuring initialization only occurs once. return 0; } function _getTotalTokens() internal view virtual override returns (uint256) { return _TOTAL_TOKENS; } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { if (token == _mainToken) { return _scalingFactorMainToken; } else if (token == _wrappedToken) { // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token // increases in value. return _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); } else if (token == this) { return FixedPoint.ONE; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS); // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in // value. scalingFactors[_mainIndex] = _scalingFactorMainToken; scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); scalingFactors[_bptIndex] = FixedPoint.ONE; return scalingFactors; } // Price rates /** * @dev For a Linear Pool, the rate represents the appreciation of BPT with respect to the underlying tokens. This * rate increases slowly as the wrapped token appreciates in value. */ function getRate() external view override returns (uint256) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); _upscaleArray(balances, _scalingFactors()); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); uint256 totalBalance = LinearMath._calcInvariant( LinearMath._toNominal(balances[_mainIndex], params), balances[_wrappedIndex] ); // Note that we're dividing by the virtual supply, which may be zero (causing this call to revert). However, the // only way for that to happen would be for all LPs to exit the Pool, and nothing prevents new LPs from // joining it later on. return totalBalance.divUp(_getApproximateVirtualSupply(balances[_bptIndex])); } function getWrappedTokenRate() external view returns (uint256) { return _getWrappedTokenRate(); } function _getWrappedTokenRate() internal view virtual returns (uint256); function getTargets() public view returns (uint256 lowerTarget, uint256 upperTarget) { bytes32 miscData = _getMiscData(); lowerTarget = miscData.decodeUint96(_LOWER_TARGET_OFFSET); upperTarget = miscData.decodeUint96(_UPPER_TARGET_OFFSET); } function _setTargets( IERC20 mainToken, uint256 lowerTarget, uint256 upperTarget ) private { _require(lowerTarget <= upperTarget, Errors.LOWER_GREATER_THAN_UPPER_TARGET); _require(upperTarget <= _MAX_UPPER_TARGET, Errors.UPPER_TARGET_TOO_HIGH); // Pack targets as two uint96 values into a single storage slot. This results in targets being capped to 96 // bits, but that should be more than enough. _setMiscData( WordCodec.encodeUint(lowerTarget, _LOWER_TARGET_OFFSET) | WordCodec.encodeUint(upperTarget, _UPPER_TARGET_OFFSET) ); emit TargetsSet(mainToken, lowerTarget, upperTarget); } function setTargets(uint256 newLowerTarget, uint256 newUpperTarget) external authenticate { // For a new target range to be valid: // - the pool must currently be between the current targets (meaning no fees are currently pending) // - the pool must currently be between the new targets (meaning setting them does not cause for fees to be // pending) // // The first requirement could be relaxed, as the LPs actually benefit from the pending fees not being paid out, // but being stricter makes analysis easier at little expense. (uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE); _require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE); _setTargets(_mainToken, newLowerTarget, newUpperTarget); } function setSwapFeePercentage(uint256 swapFeePercentage) public override { // For the swap fee percentage to be changeable: // - the pool must currently be between the current targets (meaning no fees are currently pending) // // As the amount of accrued fees is not explicitly stored but rather derived from the main token balance and the // current swap fee percentage, requiring for no fees to be pending prevents the fee setter from changing the // amount of pending fees, which they could use to e.g. drain Pool funds in the form of inflated fees. (uint256 lowerTarget, uint256 upperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(lowerTarget, upperTarget), Errors.OUT_OF_TARGET_RANGE); super.setSwapFeePercentage(swapFeePercentage); } function _isMainBalanceWithinTargets(uint256 lowerTarget, uint256 upperTarget) private view returns (bool) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); uint256 mainTokenBalance = _upscale(balances[_mainIndex], _scalingFactor(_mainToken)); return mainTokenBalance >= lowerTarget && mainTokenBalance <= upperTarget; } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return actionId == getActionId(this.setTargets.selector) || super._isOwnerOnlyAction(actionId); } /** * @dev Returns the number of tokens in circulation. * * In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` * remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it. */ function getVirtualSupply() external view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has // 18 decimals), but we do it for completeness. uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this)); return _getVirtualSupply(bptBalance); } function _getVirtualSupply(uint256 bptBalance) internal view returns (uint256) { return totalSupply().sub(bptBalance); } /** * @dev Computes an approximation of virtual supply, which costs less gas than `_getVirtualSupply` and returns the * same value in all cases except when the emergency pause has been enabled and BPT burned as part of the emergency * exit process. */ function _getApproximateVirtualSupply(uint256 bptBalance) internal pure returns (uint256) { // No need for checked arithmetic as _INITIAL_BPT_SUPPLY is always greater than any valid Vault BPT balance. return _INITIAL_BPT_SUPPLY - bptBalance; } }
/** * @dev Linear Pools are designed to hold two assets: "main" and "wrapped" tokens that have an equal value underlying * token (e.g., DAI and waDAI). There must be an external feed available to provide an exact, non-manipulable exchange * rate between the tokens. In particular, any reversible manipulation (e.g. causing the rate to increase and then * decrease) can lead to severe issues and loss of funds. * * The Pool will register three tokens in the Vault however: the two assets and the BPT itself, * so that BPT can be exchanged (effectively joining and exiting) via swaps. * * Despite inheriting from BasePool, much of the basic behavior changes. This Pool does not support regular joins and * exits, as the entire BPT supply is 'preminted' during initialization. * * Unlike most other Pools, this one does not attempt to create revenue by charging fees: value is derived by holding * the wrapped, yield-bearing asset. However, the 'swap fee percentage' value is still used, albeit with a different * meaning. This Pool attempts to hold a certain amount of "main" tokens, between a lower and upper target value. * The pool charges fees on trades that move the balance outside that range, which are then paid back as incentives to * traders whose swaps return the balance to the desired region. * The net revenue via fees is expected to be zero: all collected fees are used to pay for this 'rebalancing'. */
NatSpecMultiLine
getRate
function getRate() external view override returns (uint256) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); _upscaleArray(balances, _scalingFactors()); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); uint256 totalBalance = LinearMath._calcInvariant( LinearMath._toNominal(balances[_mainIndex], params), balances[_wrappedIndex] ); // Note that we're dividing by the virtual supply, which may be zero (causing this call to revert). However, the // only way for that to happen would be for all LPs to exit the Pool, and nothing prevents new LPs from // joining it later on. return totalBalance.divUp(_getApproximateVirtualSupply(balances[_bptIndex])); }
/** * @dev For a Linear Pool, the rate represents the appreciation of BPT with respect to the underlying tokens. This * rate increases slowly as the wrapped token appreciates in value. */
NatSpecMultiLine
v0.7.1+commit.f4a555be
{ "func_code_index": [ 21050, 22068 ] }
54,326
AaveLinearPool
contracts/LinearPool.sol
0x652d486b80c461c397b0d95612a404da936f3db3
Solidity
LinearPool
abstract contract LinearPool is BasePool, IGeneralPool, IRateProvider { using WordCodec for bytes32; using FixedPoint for uint256; using PriceRateCache for bytes32; using LinearPoolUserData for bytes; uint256 private constant _TOTAL_TOKENS = 3; // Main token, wrapped token, BPT // This is the maximum token amount the Vault can hold. In regular operation, the total BPT supply remains constant // and equal to _INITIAL_BPT_SUPPLY, but most of it remains in the Pool, waiting to be exchanged for tokens. The // actual amount of BPT in circulation is the total supply minus the amount held by the Pool, and is known as the // 'virtual supply'. // The total supply can only change if the emergency pause is activated by governance, enabling an // alternative proportional exit that burns BPT. As this is not expected to happen, we optimize for // success by using _INITIAL_BPT_SUPPLY instead of totalSupply(), saving a storage read. This optimization is only // valid if the Pool is never paused: in case of an emergency that leads to burned tokens, the Pool should not // be used after the buffer period expires and it automatically 'unpauses'. uint256 private constant _INITIAL_BPT_SUPPLY = 2**(112) - 1; IERC20 private immutable _mainToken; IERC20 private immutable _wrappedToken; // The indices of each token when registered, which can then be used to access the balances array. uint256 private immutable _bptIndex; uint256 private immutable _mainIndex; uint256 private immutable _wrappedIndex; // Both BPT and the main token have a regular, constant scaling factor (equal to FixedPoint.ONE for BPT, and // dependent on the number of decimals for the main token). However, the wrapped token's scaling factor has two // components: the usual token decimal scaling factor, and an externally provided rate used to convert wrapped // tokens to an equivalent main token amount. This external rate is expected to be ever increasing, reflecting the // fact that the wrapped token appreciates in value over time (e.g. because it is accruing interest). uint256 private immutable _scalingFactorMainToken; uint256 private immutable _scalingFactorWrappedToken; // The lower and upper target are in BasePool's misc data field, which has 192 bits available (as it shares the same // storage slot as the swap fee percentage, which is 64 bits). These are already scaled by the main token's scaling // factor, which means that the maximum upper target is ~80 billion in the main token units if the token were to // have 18 decimals (2^(192/2) / 10^18), which is more than enough. // [ 64 bits | 96 bits | 96 bits ] // [ reserved | upper target | lower target ] // [ base pool swap fee | misc data ] // [ MSB LSB ] uint256 private constant _LOWER_TARGET_OFFSET = 0; uint256 private constant _UPPER_TARGET_OFFSET = 96; uint256 private constant _MAX_UPPER_TARGET = 2**(96) - 1; event TargetsSet(IERC20 indexed token, uint256 lowerTarget, uint256 upperTarget); constructor( IVault vault, string memory name, string memory symbol, IERC20 mainToken, IERC20 wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, IVault.PoolSpecialization.GENERAL, name, symbol, _sortTokens(mainToken, wrappedToken, this), new address[](_TOTAL_TOKENS), swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // Set tokens _mainToken = mainToken; _wrappedToken = wrappedToken; // Set token indexes (uint256 mainIndex, uint256 wrappedIndex, uint256 bptIndex) = _getSortedTokenIndexes( mainToken, wrappedToken, this ); _bptIndex = bptIndex; _mainIndex = mainIndex; _wrappedIndex = wrappedIndex; // Set scaling factors _scalingFactorMainToken = _computeScalingFactor(mainToken); _scalingFactorWrappedToken = _computeScalingFactor(wrappedToken); // Set initial targets. Lower target must be set to zero because initially there are no fees accumulated. // Otherwise the pool will owe fees at start which results in a manipulable rate. uint256 lowerTarget = 0; _setTargets(mainToken, lowerTarget, upperTarget); } function getMainToken() public view returns (address) { return address(_mainToken); } function getWrappedToken() external view returns (address) { return address(_wrappedToken); } function getBptIndex() external view returns (uint256) { return _bptIndex; } function getMainIndex() external view returns (uint256) { return _mainIndex; } function getWrappedIndex() external view returns (uint256) { return _wrappedIndex; } /** * @dev Finishes initialization of the Linear Pool: it is unusable before calling this function as no BPT will have * been minted. * * Since Linear Pools have preminted BPT stored in the Vault, they require an initial join to deposit said BPT as * their balance. Unfortunately, this cannot be performed during construction, as a join involves calling the * `onJoinPool` function on the Pool, and the Pool will not have any code until construction finishes. Therefore, * this must happen in a separate call. * * It is highly recommended to create Linear pools using the LinearPoolFactory, which calls `initialize` * automatically. */ function initialize() external { bytes32 poolId = getPoolId(); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(poolId); // Joins typically involve the Pool receiving tokens in exchange for newly-minted BPT. In this case however, the // Pool will mint the entire BPT supply to itself, and join itself with it. uint256[] memory maxAmountsIn = new uint256[](_TOTAL_TOKENS); maxAmountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; // The first time this executes, it will call `_onInitializePool` (as the BPT supply will be zero). Future calls // will be routed to `_onJoinPool`, which always reverts, meaning `initialize` will only execute once. IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: _asIAsset(tokens), maxAmountsIn: maxAmountsIn, userData: "", fromInternalBalance: false }); getVault().joinPool(poolId, address(this), address(this), request); } /** * @dev Implementation of onSwap, from IGeneralPool. */ function onSwap( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public view override onlyVault(request.poolId) whenNotPaused returns (uint256) { // In most Pools, swaps involve exchanging one token held by the Pool for another. In this case however, since // one of the three tokens is the BPT itself, a swap might also be a join (main/wrapped for BPT) or an exit // (BPT for main/wrapped). // All three swap types (swaps, joins and exits) are fully disabled if the emergency pause is enabled. Under // these circumstances, the Pool should be exited using the regular Vault.exitPool function. // Sanity check: this is not entirely necessary as the Vault's interface enforces the indices to be valid, but // the check is cheap to perform. _require(indexIn < _TOTAL_TOKENS && indexOut < _TOTAL_TOKENS, Errors.OUT_OF_BOUNDS); // Note that we already know the indices of the main token, wrapped token and BPT, so there is no need to pass // these indices to the inner functions. // Upscale balances by the scaling factors (taking into account the wrapped token rate) uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); if (request.kind == IVault.SwapKind.GIVEN_IN) { // The amount given is for token in, the amount calculated is for token out request.amount = _upscale(request.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(request, balances, params); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } else { // The amount given is for token out, the amount calculated is for token in request.amount = _upscale(request.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(request, balances, params); // amountIn tokens are entering the Pool, so we round up. return _downscaleUp(amountIn, scalingFactors[indexIn]); } } function _onSwapGivenIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenIn == this) { return _swapGivenBptIn(request, balances, params); } else if (request.tokenIn == _mainToken) { return _swapGivenMainIn(request, balances, params); } else if (request.tokenIn == _wrappedToken) { return _swapGivenWrappedIn(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenOut == _mainToken ? LinearMath._calcMainOutPerBptIn : LinearMath._calcWrappedOutPerBptIn)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _wrappedToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerMainIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedOutPerMainIn(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerWrappedIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainOutPerWrappedIn(request.amount, balances[_mainIndex], params); } function _onSwapGivenOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenOut == this) { return _swapGivenBptOut(request, balances, params); } else if (request.tokenOut == _mainToken) { return _swapGivenMainOut(request, balances, params); } else if (request.tokenOut == _wrappedToken) { return _swapGivenWrappedOut(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenIn == _mainToken ? LinearMath._calcMainInPerBptOut : LinearMath._calcWrappedInPerBptOut)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _wrappedToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerMainOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedInPerMainOut(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerWrappedOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainInPerWrappedOut(request.amount, balances[_mainIndex], params); } function _onInitializePool( bytes32, address sender, address recipient, uint256[] memory, bytes memory ) internal view override whenNotPaused returns (uint256, uint256[] memory) { // Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function. _require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION); // The full BPT supply will be minted and deposited in the Pool. Note that there is no need to approve the Vault // as it already has infinite BPT allowance. uint256 bptAmountOut = _INITIAL_BPT_SUPPLY; uint256[] memory amountsIn = new uint256[](_TOTAL_TOKENS); amountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; return (bptAmountOut, amountsIn); } function _onJoinPool( bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory ) internal pure override returns ( uint256, uint256[] memory, uint256[] memory ) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256, uint256[] memory, bytes memory userData ) internal view override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits typically revert, except for the proportional exit when the emergency pause mechanism has been // triggered. This allows for a simple and safe way to exit the Pool. // Note that the rate cache will not be automatically updated in such a scenario (though this can be still done // manually). This however should not lead to any issues as the rate is not important during the emergency exit. // On the contrary, decoupling the rate provider from the emergency exit might be useful under these // circumstances. LinearPoolUserData.ExitKind kind = userData.exitKind(); if (kind != LinearPoolUserData.ExitKind.EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } else { _ensurePaused(); // Note that this will cause the user's BPT to be burned, which is not something that happens during // regular operation of this Pool, and may lead to accounting errors. Because of this, it is highly // advisable to stop using a Pool after it is paused and the pause window expires. (bptAmountIn, amountsOut) = _emergencyProportionalExit(balances, userData); // Due protocol fees are set to zero as this Pool accrues no fees and pays no protocol fees. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } } function _emergencyProportionalExit(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This proportional exit function is only enabled if the contract is paused, to provide users a way to // retrieve their tokens in case of an emergency. // // This particular exit function is the only one available because it is the simplest, and therefore least // likely to be incorrect, or revert and lock funds. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. // This process burns BPT, rendering `_getApproximateVirtualSupply` inaccurate, so we use the real method here uint256[] memory amountsOut = LinearMath._calcTokensOutGivenExactBptIn( balances, bptAmountIn, _getVirtualSupply(balances[_bptIndex]), _bptIndex ); return (bptAmountIn, amountsOut); } function _getMaxTokens() internal pure override returns (uint256) { return _TOTAL_TOKENS; } function _getMinimumBpt() internal pure override returns (uint256) { // Linear Pools don't lock any BPT, as the total supply will already be forever non-zero due to the preminting // mechanism, ensuring initialization only occurs once. return 0; } function _getTotalTokens() internal view virtual override returns (uint256) { return _TOTAL_TOKENS; } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { if (token == _mainToken) { return _scalingFactorMainToken; } else if (token == _wrappedToken) { // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token // increases in value. return _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); } else if (token == this) { return FixedPoint.ONE; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS); // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in // value. scalingFactors[_mainIndex] = _scalingFactorMainToken; scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); scalingFactors[_bptIndex] = FixedPoint.ONE; return scalingFactors; } // Price rates /** * @dev For a Linear Pool, the rate represents the appreciation of BPT with respect to the underlying tokens. This * rate increases slowly as the wrapped token appreciates in value. */ function getRate() external view override returns (uint256) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); _upscaleArray(balances, _scalingFactors()); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); uint256 totalBalance = LinearMath._calcInvariant( LinearMath._toNominal(balances[_mainIndex], params), balances[_wrappedIndex] ); // Note that we're dividing by the virtual supply, which may be zero (causing this call to revert). However, the // only way for that to happen would be for all LPs to exit the Pool, and nothing prevents new LPs from // joining it later on. return totalBalance.divUp(_getApproximateVirtualSupply(balances[_bptIndex])); } function getWrappedTokenRate() external view returns (uint256) { return _getWrappedTokenRate(); } function _getWrappedTokenRate() internal view virtual returns (uint256); function getTargets() public view returns (uint256 lowerTarget, uint256 upperTarget) { bytes32 miscData = _getMiscData(); lowerTarget = miscData.decodeUint96(_LOWER_TARGET_OFFSET); upperTarget = miscData.decodeUint96(_UPPER_TARGET_OFFSET); } function _setTargets( IERC20 mainToken, uint256 lowerTarget, uint256 upperTarget ) private { _require(lowerTarget <= upperTarget, Errors.LOWER_GREATER_THAN_UPPER_TARGET); _require(upperTarget <= _MAX_UPPER_TARGET, Errors.UPPER_TARGET_TOO_HIGH); // Pack targets as two uint96 values into a single storage slot. This results in targets being capped to 96 // bits, but that should be more than enough. _setMiscData( WordCodec.encodeUint(lowerTarget, _LOWER_TARGET_OFFSET) | WordCodec.encodeUint(upperTarget, _UPPER_TARGET_OFFSET) ); emit TargetsSet(mainToken, lowerTarget, upperTarget); } function setTargets(uint256 newLowerTarget, uint256 newUpperTarget) external authenticate { // For a new target range to be valid: // - the pool must currently be between the current targets (meaning no fees are currently pending) // - the pool must currently be between the new targets (meaning setting them does not cause for fees to be // pending) // // The first requirement could be relaxed, as the LPs actually benefit from the pending fees not being paid out, // but being stricter makes analysis easier at little expense. (uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE); _require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE); _setTargets(_mainToken, newLowerTarget, newUpperTarget); } function setSwapFeePercentage(uint256 swapFeePercentage) public override { // For the swap fee percentage to be changeable: // - the pool must currently be between the current targets (meaning no fees are currently pending) // // As the amount of accrued fees is not explicitly stored but rather derived from the main token balance and the // current swap fee percentage, requiring for no fees to be pending prevents the fee setter from changing the // amount of pending fees, which they could use to e.g. drain Pool funds in the form of inflated fees. (uint256 lowerTarget, uint256 upperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(lowerTarget, upperTarget), Errors.OUT_OF_TARGET_RANGE); super.setSwapFeePercentage(swapFeePercentage); } function _isMainBalanceWithinTargets(uint256 lowerTarget, uint256 upperTarget) private view returns (bool) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); uint256 mainTokenBalance = _upscale(balances[_mainIndex], _scalingFactor(_mainToken)); return mainTokenBalance >= lowerTarget && mainTokenBalance <= upperTarget; } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return actionId == getActionId(this.setTargets.selector) || super._isOwnerOnlyAction(actionId); } /** * @dev Returns the number of tokens in circulation. * * In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` * remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it. */ function getVirtualSupply() external view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has // 18 decimals), but we do it for completeness. uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this)); return _getVirtualSupply(bptBalance); } function _getVirtualSupply(uint256 bptBalance) internal view returns (uint256) { return totalSupply().sub(bptBalance); } /** * @dev Computes an approximation of virtual supply, which costs less gas than `_getVirtualSupply` and returns the * same value in all cases except when the emergency pause has been enabled and BPT burned as part of the emergency * exit process. */ function _getApproximateVirtualSupply(uint256 bptBalance) internal pure returns (uint256) { // No need for checked arithmetic as _INITIAL_BPT_SUPPLY is always greater than any valid Vault BPT balance. return _INITIAL_BPT_SUPPLY - bptBalance; } }
/** * @dev Linear Pools are designed to hold two assets: "main" and "wrapped" tokens that have an equal value underlying * token (e.g., DAI and waDAI). There must be an external feed available to provide an exact, non-manipulable exchange * rate between the tokens. In particular, any reversible manipulation (e.g. causing the rate to increase and then * decrease) can lead to severe issues and loss of funds. * * The Pool will register three tokens in the Vault however: the two assets and the BPT itself, * so that BPT can be exchanged (effectively joining and exiting) via swaps. * * Despite inheriting from BasePool, much of the basic behavior changes. This Pool does not support regular joins and * exits, as the entire BPT supply is 'preminted' during initialization. * * Unlike most other Pools, this one does not attempt to create revenue by charging fees: value is derived by holding * the wrapped, yield-bearing asset. However, the 'swap fee percentage' value is still used, albeit with a different * meaning. This Pool attempts to hold a certain amount of "main" tokens, between a lower and upper target value. * The pool charges fees on trades that move the balance outside that range, which are then paid back as incentives to * traders whose swaps return the balance to the desired region. * The net revenue via fees is expected to be zero: all collected fees are used to pay for this 'rebalancing'. */
NatSpecMultiLine
getVirtualSupply
function getVirtualSupply() external view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has // 18 decimals), but we do it for completeness. uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this)); return _getVirtualSupply(bptBalance); }
/** * @dev Returns the number of tokens in circulation. * * In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` * remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it. */
NatSpecMultiLine
v0.7.1+commit.f4a555be
{ "func_code_index": [ 25993, 26447 ] }
54,327
AaveLinearPool
contracts/LinearPool.sol
0x652d486b80c461c397b0d95612a404da936f3db3
Solidity
LinearPool
abstract contract LinearPool is BasePool, IGeneralPool, IRateProvider { using WordCodec for bytes32; using FixedPoint for uint256; using PriceRateCache for bytes32; using LinearPoolUserData for bytes; uint256 private constant _TOTAL_TOKENS = 3; // Main token, wrapped token, BPT // This is the maximum token amount the Vault can hold. In regular operation, the total BPT supply remains constant // and equal to _INITIAL_BPT_SUPPLY, but most of it remains in the Pool, waiting to be exchanged for tokens. The // actual amount of BPT in circulation is the total supply minus the amount held by the Pool, and is known as the // 'virtual supply'. // The total supply can only change if the emergency pause is activated by governance, enabling an // alternative proportional exit that burns BPT. As this is not expected to happen, we optimize for // success by using _INITIAL_BPT_SUPPLY instead of totalSupply(), saving a storage read. This optimization is only // valid if the Pool is never paused: in case of an emergency that leads to burned tokens, the Pool should not // be used after the buffer period expires and it automatically 'unpauses'. uint256 private constant _INITIAL_BPT_SUPPLY = 2**(112) - 1; IERC20 private immutable _mainToken; IERC20 private immutable _wrappedToken; // The indices of each token when registered, which can then be used to access the balances array. uint256 private immutable _bptIndex; uint256 private immutable _mainIndex; uint256 private immutable _wrappedIndex; // Both BPT and the main token have a regular, constant scaling factor (equal to FixedPoint.ONE for BPT, and // dependent on the number of decimals for the main token). However, the wrapped token's scaling factor has two // components: the usual token decimal scaling factor, and an externally provided rate used to convert wrapped // tokens to an equivalent main token amount. This external rate is expected to be ever increasing, reflecting the // fact that the wrapped token appreciates in value over time (e.g. because it is accruing interest). uint256 private immutable _scalingFactorMainToken; uint256 private immutable _scalingFactorWrappedToken; // The lower and upper target are in BasePool's misc data field, which has 192 bits available (as it shares the same // storage slot as the swap fee percentage, which is 64 bits). These are already scaled by the main token's scaling // factor, which means that the maximum upper target is ~80 billion in the main token units if the token were to // have 18 decimals (2^(192/2) / 10^18), which is more than enough. // [ 64 bits | 96 bits | 96 bits ] // [ reserved | upper target | lower target ] // [ base pool swap fee | misc data ] // [ MSB LSB ] uint256 private constant _LOWER_TARGET_OFFSET = 0; uint256 private constant _UPPER_TARGET_OFFSET = 96; uint256 private constant _MAX_UPPER_TARGET = 2**(96) - 1; event TargetsSet(IERC20 indexed token, uint256 lowerTarget, uint256 upperTarget); constructor( IVault vault, string memory name, string memory symbol, IERC20 mainToken, IERC20 wrappedToken, uint256 upperTarget, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BasePool( vault, IVault.PoolSpecialization.GENERAL, name, symbol, _sortTokens(mainToken, wrappedToken, this), new address[](_TOTAL_TOKENS), swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) { // Set tokens _mainToken = mainToken; _wrappedToken = wrappedToken; // Set token indexes (uint256 mainIndex, uint256 wrappedIndex, uint256 bptIndex) = _getSortedTokenIndexes( mainToken, wrappedToken, this ); _bptIndex = bptIndex; _mainIndex = mainIndex; _wrappedIndex = wrappedIndex; // Set scaling factors _scalingFactorMainToken = _computeScalingFactor(mainToken); _scalingFactorWrappedToken = _computeScalingFactor(wrappedToken); // Set initial targets. Lower target must be set to zero because initially there are no fees accumulated. // Otherwise the pool will owe fees at start which results in a manipulable rate. uint256 lowerTarget = 0; _setTargets(mainToken, lowerTarget, upperTarget); } function getMainToken() public view returns (address) { return address(_mainToken); } function getWrappedToken() external view returns (address) { return address(_wrappedToken); } function getBptIndex() external view returns (uint256) { return _bptIndex; } function getMainIndex() external view returns (uint256) { return _mainIndex; } function getWrappedIndex() external view returns (uint256) { return _wrappedIndex; } /** * @dev Finishes initialization of the Linear Pool: it is unusable before calling this function as no BPT will have * been minted. * * Since Linear Pools have preminted BPT stored in the Vault, they require an initial join to deposit said BPT as * their balance. Unfortunately, this cannot be performed during construction, as a join involves calling the * `onJoinPool` function on the Pool, and the Pool will not have any code until construction finishes. Therefore, * this must happen in a separate call. * * It is highly recommended to create Linear pools using the LinearPoolFactory, which calls `initialize` * automatically. */ function initialize() external { bytes32 poolId = getPoolId(); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(poolId); // Joins typically involve the Pool receiving tokens in exchange for newly-minted BPT. In this case however, the // Pool will mint the entire BPT supply to itself, and join itself with it. uint256[] memory maxAmountsIn = new uint256[](_TOTAL_TOKENS); maxAmountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; // The first time this executes, it will call `_onInitializePool` (as the BPT supply will be zero). Future calls // will be routed to `_onJoinPool`, which always reverts, meaning `initialize` will only execute once. IVault.JoinPoolRequest memory request = IVault.JoinPoolRequest({ assets: _asIAsset(tokens), maxAmountsIn: maxAmountsIn, userData: "", fromInternalBalance: false }); getVault().joinPool(poolId, address(this), address(this), request); } /** * @dev Implementation of onSwap, from IGeneralPool. */ function onSwap( SwapRequest memory request, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) public view override onlyVault(request.poolId) whenNotPaused returns (uint256) { // In most Pools, swaps involve exchanging one token held by the Pool for another. In this case however, since // one of the three tokens is the BPT itself, a swap might also be a join (main/wrapped for BPT) or an exit // (BPT for main/wrapped). // All three swap types (swaps, joins and exits) are fully disabled if the emergency pause is enabled. Under // these circumstances, the Pool should be exited using the regular Vault.exitPool function. // Sanity check: this is not entirely necessary as the Vault's interface enforces the indices to be valid, but // the check is cheap to perform. _require(indexIn < _TOTAL_TOKENS && indexOut < _TOTAL_TOKENS, Errors.OUT_OF_BOUNDS); // Note that we already know the indices of the main token, wrapped token and BPT, so there is no need to pass // these indices to the inner functions. // Upscale balances by the scaling factors (taking into account the wrapped token rate) uint256[] memory scalingFactors = _scalingFactors(); _upscaleArray(balances, scalingFactors); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); if (request.kind == IVault.SwapKind.GIVEN_IN) { // The amount given is for token in, the amount calculated is for token out request.amount = _upscale(request.amount, scalingFactors[indexIn]); uint256 amountOut = _onSwapGivenIn(request, balances, params); // amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); } else { // The amount given is for token out, the amount calculated is for token in request.amount = _upscale(request.amount, scalingFactors[indexOut]); uint256 amountIn = _onSwapGivenOut(request, balances, params); // amountIn tokens are entering the Pool, so we round up. return _downscaleUp(amountIn, scalingFactors[indexIn]); } } function _onSwapGivenIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenIn == this) { return _swapGivenBptIn(request, balances, params); } else if (request.tokenIn == _mainToken) { return _swapGivenMainIn(request, balances, params); } else if (request.tokenIn == _wrappedToken) { return _swapGivenWrappedIn(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenOut == _mainToken ? LinearMath._calcMainOutPerBptIn : LinearMath._calcWrappedOutPerBptIn)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _wrappedToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerMainIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedOutPerMainIn(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedIn( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenOut == _mainToken || request.tokenOut == this, Errors.INVALID_TOKEN); return request.tokenOut == this ? LinearMath._calcBptOutPerWrappedIn( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainOutPerWrappedIn(request.amount, balances[_mainIndex], params); } function _onSwapGivenOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { if (request.tokenOut == this) { return _swapGivenBptOut(request, balances, params); } else if (request.tokenOut == _mainToken) { return _swapGivenMainOut(request, balances, params); } else if (request.tokenOut == _wrappedToken) { return _swapGivenWrappedOut(request, balances, params); } else { _revert(Errors.INVALID_TOKEN); } } function _swapGivenBptOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == _wrappedToken, Errors.INVALID_TOKEN); return (request.tokenIn == _mainToken ? LinearMath._calcMainInPerBptOut : LinearMath._calcWrappedInPerBptOut)( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ); } function _swapGivenMainOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _wrappedToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerMainOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcWrappedInPerMainOut(request.amount, balances[_mainIndex], params); } function _swapGivenWrappedOut( SwapRequest memory request, uint256[] memory balances, LinearMath.Params memory params ) internal view returns (uint256) { _require(request.tokenIn == _mainToken || request.tokenIn == this, Errors.INVALID_TOKEN); return request.tokenIn == this ? LinearMath._calcBptInPerWrappedOut( request.amount, balances[_mainIndex], balances[_wrappedIndex], _getApproximateVirtualSupply(balances[_bptIndex]), params ) : LinearMath._calcMainInPerWrappedOut(request.amount, balances[_mainIndex], params); } function _onInitializePool( bytes32, address sender, address recipient, uint256[] memory, bytes memory ) internal view override whenNotPaused returns (uint256, uint256[] memory) { // Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function. _require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION); // The full BPT supply will be minted and deposited in the Pool. Note that there is no need to approve the Vault // as it already has infinite BPT allowance. uint256 bptAmountOut = _INITIAL_BPT_SUPPLY; uint256[] memory amountsIn = new uint256[](_TOTAL_TOKENS); amountsIn[_bptIndex] = _INITIAL_BPT_SUPPLY; return (bptAmountOut, amountsIn); } function _onJoinPool( bytes32, address, address, uint256[] memory, uint256, uint256, uint256[] memory, bytes memory ) internal pure override returns ( uint256, uint256[] memory, uint256[] memory ) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256, uint256[] memory, bytes memory userData ) internal view override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits typically revert, except for the proportional exit when the emergency pause mechanism has been // triggered. This allows for a simple and safe way to exit the Pool. // Note that the rate cache will not be automatically updated in such a scenario (though this can be still done // manually). This however should not lead to any issues as the rate is not important during the emergency exit. // On the contrary, decoupling the rate provider from the emergency exit might be useful under these // circumstances. LinearPoolUserData.ExitKind kind = userData.exitKind(); if (kind != LinearPoolUserData.ExitKind.EMERGENCY_EXACT_BPT_IN_FOR_TOKENS_OUT) { _revert(Errors.UNHANDLED_BY_LINEAR_POOL); } else { _ensurePaused(); // Note that this will cause the user's BPT to be burned, which is not something that happens during // regular operation of this Pool, and may lead to accounting errors. Because of this, it is highly // advisable to stop using a Pool after it is paused and the pause window expires. (bptAmountIn, amountsOut) = _emergencyProportionalExit(balances, userData); // Due protocol fees are set to zero as this Pool accrues no fees and pays no protocol fees. dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } } function _emergencyProportionalExit(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { // This proportional exit function is only enabled if the contract is paused, to provide users a way to // retrieve their tokens in case of an emergency. // // This particular exit function is the only one available because it is the simplest, and therefore least // likely to be incorrect, or revert and lock funds. uint256 bptAmountIn = userData.exactBptInForTokensOut(); // Note that there is no minimum amountOut parameter: this is handled by `IVault.exitPool`. // This process burns BPT, rendering `_getApproximateVirtualSupply` inaccurate, so we use the real method here uint256[] memory amountsOut = LinearMath._calcTokensOutGivenExactBptIn( balances, bptAmountIn, _getVirtualSupply(balances[_bptIndex]), _bptIndex ); return (bptAmountIn, amountsOut); } function _getMaxTokens() internal pure override returns (uint256) { return _TOTAL_TOKENS; } function _getMinimumBpt() internal pure override returns (uint256) { // Linear Pools don't lock any BPT, as the total supply will already be forever non-zero due to the preminting // mechanism, ensuring initialization only occurs once. return 0; } function _getTotalTokens() internal view virtual override returns (uint256) { return _TOTAL_TOKENS; } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { if (token == _mainToken) { return _scalingFactorMainToken; } else if (token == _wrappedToken) { // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token // increases in value. return _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); } else if (token == this) { return FixedPoint.ONE; } else { _revert(Errors.INVALID_TOKEN); } } function _scalingFactors() internal view virtual override returns (uint256[] memory) { uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS); // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in // value. scalingFactors[_mainIndex] = _scalingFactorMainToken; scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate()); scalingFactors[_bptIndex] = FixedPoint.ONE; return scalingFactors; } // Price rates /** * @dev For a Linear Pool, the rate represents the appreciation of BPT with respect to the underlying tokens. This * rate increases slowly as the wrapped token appreciates in value. */ function getRate() external view override returns (uint256) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); _upscaleArray(balances, _scalingFactors()); (uint256 lowerTarget, uint256 upperTarget) = getTargets(); LinearMath.Params memory params = LinearMath.Params({ fee: getSwapFeePercentage(), lowerTarget: lowerTarget, upperTarget: upperTarget }); uint256 totalBalance = LinearMath._calcInvariant( LinearMath._toNominal(balances[_mainIndex], params), balances[_wrappedIndex] ); // Note that we're dividing by the virtual supply, which may be zero (causing this call to revert). However, the // only way for that to happen would be for all LPs to exit the Pool, and nothing prevents new LPs from // joining it later on. return totalBalance.divUp(_getApproximateVirtualSupply(balances[_bptIndex])); } function getWrappedTokenRate() external view returns (uint256) { return _getWrappedTokenRate(); } function _getWrappedTokenRate() internal view virtual returns (uint256); function getTargets() public view returns (uint256 lowerTarget, uint256 upperTarget) { bytes32 miscData = _getMiscData(); lowerTarget = miscData.decodeUint96(_LOWER_TARGET_OFFSET); upperTarget = miscData.decodeUint96(_UPPER_TARGET_OFFSET); } function _setTargets( IERC20 mainToken, uint256 lowerTarget, uint256 upperTarget ) private { _require(lowerTarget <= upperTarget, Errors.LOWER_GREATER_THAN_UPPER_TARGET); _require(upperTarget <= _MAX_UPPER_TARGET, Errors.UPPER_TARGET_TOO_HIGH); // Pack targets as two uint96 values into a single storage slot. This results in targets being capped to 96 // bits, but that should be more than enough. _setMiscData( WordCodec.encodeUint(lowerTarget, _LOWER_TARGET_OFFSET) | WordCodec.encodeUint(upperTarget, _UPPER_TARGET_OFFSET) ); emit TargetsSet(mainToken, lowerTarget, upperTarget); } function setTargets(uint256 newLowerTarget, uint256 newUpperTarget) external authenticate { // For a new target range to be valid: // - the pool must currently be between the current targets (meaning no fees are currently pending) // - the pool must currently be between the new targets (meaning setting them does not cause for fees to be // pending) // // The first requirement could be relaxed, as the LPs actually benefit from the pending fees not being paid out, // but being stricter makes analysis easier at little expense. (uint256 currentLowerTarget, uint256 currentUpperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(currentLowerTarget, currentUpperTarget), Errors.OUT_OF_TARGET_RANGE); _require(_isMainBalanceWithinTargets(newLowerTarget, newUpperTarget), Errors.OUT_OF_NEW_TARGET_RANGE); _setTargets(_mainToken, newLowerTarget, newUpperTarget); } function setSwapFeePercentage(uint256 swapFeePercentage) public override { // For the swap fee percentage to be changeable: // - the pool must currently be between the current targets (meaning no fees are currently pending) // // As the amount of accrued fees is not explicitly stored but rather derived from the main token balance and the // current swap fee percentage, requiring for no fees to be pending prevents the fee setter from changing the // amount of pending fees, which they could use to e.g. drain Pool funds in the form of inflated fees. (uint256 lowerTarget, uint256 upperTarget) = getTargets(); _require(_isMainBalanceWithinTargets(lowerTarget, upperTarget), Errors.OUT_OF_TARGET_RANGE); super.setSwapFeePercentage(swapFeePercentage); } function _isMainBalanceWithinTargets(uint256 lowerTarget, uint256 upperTarget) private view returns (bool) { bytes32 poolId = getPoolId(); (, uint256[] memory balances, ) = getVault().getPoolTokens(poolId); uint256 mainTokenBalance = _upscale(balances[_mainIndex], _scalingFactor(_mainToken)); return mainTokenBalance >= lowerTarget && mainTokenBalance <= upperTarget; } function _isOwnerOnlyAction(bytes32 actionId) internal view virtual override returns (bool) { return actionId == getActionId(this.setTargets.selector) || super._isOwnerOnlyAction(actionId); } /** * @dev Returns the number of tokens in circulation. * * In other pools, this would be the same as `totalSupply`, but since this pool pre-mints all BPT, `totalSupply` * remains constant, whereas `virtualSupply` increases as users join the pool and decreases as they exit it. */ function getVirtualSupply() external view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); // We technically don't need to upscale the BPT balance as its scaling factor is equal to one (since BPT has // 18 decimals), but we do it for completeness. uint256 bptBalance = _upscale(balances[_bptIndex], _scalingFactor(this)); return _getVirtualSupply(bptBalance); } function _getVirtualSupply(uint256 bptBalance) internal view returns (uint256) { return totalSupply().sub(bptBalance); } /** * @dev Computes an approximation of virtual supply, which costs less gas than `_getVirtualSupply` and returns the * same value in all cases except when the emergency pause has been enabled and BPT burned as part of the emergency * exit process. */ function _getApproximateVirtualSupply(uint256 bptBalance) internal pure returns (uint256) { // No need for checked arithmetic as _INITIAL_BPT_SUPPLY is always greater than any valid Vault BPT balance. return _INITIAL_BPT_SUPPLY - bptBalance; } }
/** * @dev Linear Pools are designed to hold two assets: "main" and "wrapped" tokens that have an equal value underlying * token (e.g., DAI and waDAI). There must be an external feed available to provide an exact, non-manipulable exchange * rate between the tokens. In particular, any reversible manipulation (e.g. causing the rate to increase and then * decrease) can lead to severe issues and loss of funds. * * The Pool will register three tokens in the Vault however: the two assets and the BPT itself, * so that BPT can be exchanged (effectively joining and exiting) via swaps. * * Despite inheriting from BasePool, much of the basic behavior changes. This Pool does not support regular joins and * exits, as the entire BPT supply is 'preminted' during initialization. * * Unlike most other Pools, this one does not attempt to create revenue by charging fees: value is derived by holding * the wrapped, yield-bearing asset. However, the 'swap fee percentage' value is still used, albeit with a different * meaning. This Pool attempts to hold a certain amount of "main" tokens, between a lower and upper target value. * The pool charges fees on trades that move the balance outside that range, which are then paid back as incentives to * traders whose swaps return the balance to the desired region. * The net revenue via fees is expected to be zero: all collected fees are used to pay for this 'rebalancing'. */
NatSpecMultiLine
_getApproximateVirtualSupply
function _getApproximateVirtualSupply(uint256 bptBalance) internal pure returns (uint256) { // No need for checked arithmetic as _INITIAL_BPT_SUPPLY is always greater than any valid Vault BPT balance. return _INITIAL_BPT_SUPPLY - bptBalance; }
/** * @dev Computes an approximation of virtual supply, which costs less gas than `_getVirtualSupply` and returns the * same value in all cases except when the emergency pause has been enabled and BPT burned as part of the emergency * exit process. */
NatSpecMultiLine
v0.7.1+commit.f4a555be
{ "func_code_index": [ 26863, 27130 ] }
54,328
ReplaySafeSplit
ReplaySafeSplit.sol
0xabbb6bebfa05aa13e908eaa492bd7a8343760477
Solidity
ReplaySafeSplit
contract ReplaySafeSplit is RequiringFunds { //address private constant oracleAddress = 0x8128B12cABc6043d94BD3C4d9B9455077Eb18807; // testnet address private constant oracleAddress = 0x2bd2326c993dfaef84f696526064ff22eba5b362; // mainnet // Fork oracle to use AmIOnTheFork amIOnTheFork = AmIOnTheFork(oracleAddress); // Splits the funds into 2 addresses function split(address targetFork, address targetNoFork) NeedEth returns(bool) { // The 2 checks are to ensure that users provide BOTH addresses // and prevent funds to be sent to 0x0 on one fork or the other. if (targetFork == 0) throw; if (targetNoFork == 0) throw; if (amIOnTheFork.forked() // if we are on the fork && targetFork.send(msg.value)) { // send the ETH to the targetFork address return true; } else if (!amIOnTheFork.forked() // if we are NOT on the fork && targetNoFork.send(msg.value)) { // send the ETH to the targetNoFork address return true; } throw; // don't accept value transfer, otherwise it would be trapped. } // Reject value transfers. function() { throw; } }
split
function split(address targetFork, address targetNoFork) NeedEth returns(bool) { // The 2 checks are to ensure that users provide BOTH addresses // and prevent funds to be sent to 0x0 on one fork or the other. if (targetFork == 0) throw; if (targetNoFork == 0) throw; if (amIOnTheFork.forked() // if we are on the fork && targetFork.send(msg.value)) { // send the ETH to the targetFork address return true; } else if (!amIOnTheFork.forked() // if we are NOT on the fork && targetNoFork.send(msg.value)) { // send the ETH to the targetNoFork address return true; } throw; // don't accept value transfer, otherwise it would be trapped. }
// Splits the funds into 2 addresses
LineComment
v0.3.5-2016-06-10-5f97274
{ "func_code_index": [ 394, 1247 ] }
54,329
ReplaySafeSplit
ReplaySafeSplit.sol
0xabbb6bebfa05aa13e908eaa492bd7a8343760477
Solidity
ReplaySafeSplit
contract ReplaySafeSplit is RequiringFunds { //address private constant oracleAddress = 0x8128B12cABc6043d94BD3C4d9B9455077Eb18807; // testnet address private constant oracleAddress = 0x2bd2326c993dfaef84f696526064ff22eba5b362; // mainnet // Fork oracle to use AmIOnTheFork amIOnTheFork = AmIOnTheFork(oracleAddress); // Splits the funds into 2 addresses function split(address targetFork, address targetNoFork) NeedEth returns(bool) { // The 2 checks are to ensure that users provide BOTH addresses // and prevent funds to be sent to 0x0 on one fork or the other. if (targetFork == 0) throw; if (targetNoFork == 0) throw; if (amIOnTheFork.forked() // if we are on the fork && targetFork.send(msg.value)) { // send the ETH to the targetFork address return true; } else if (!amIOnTheFork.forked() // if we are NOT on the fork && targetNoFork.send(msg.value)) { // send the ETH to the targetNoFork address return true; } throw; // don't accept value transfer, otherwise it would be trapped. } // Reject value transfers. function() { throw; } }
function() { throw; }
// Reject value transfers.
LineComment
v0.3.5-2016-06-10-5f97274
{ "func_code_index": [ 1282, 1322 ] }
54,330
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
tryAdd
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } }
/** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 161, 388 ] }
54,331
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
trySub
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } }
/** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 536, 735 ] }
54,332
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
tryMul
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } }
/** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 885, 1393 ] }
54,333
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
tryDiv
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } }
/** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 1544, 1744 ] }
54,334
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
tryMod
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } }
/** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 1905, 2105 ] }
54,335
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; }
/** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 2347, 2450 ] }
54,336
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; }
/** * @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.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 2728, 2831 ] }
54,337
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; }
/** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 3085, 3188 ] }
54,338
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; }
/** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 3484, 3587 ] }
54,339
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 4049, 4152 ] }
54,340
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
sub
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } }
/** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 4626, 4837 ] }
54,341
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
div
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } }
/** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 5557, 5767 ] }
54,342
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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) { return a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards 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). * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
mod
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 6425, 6635 ] }
54,343
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
isContract
function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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 * ==== */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 606, 1033 ] }
54,344
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
sendValue
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); }
/** * @dev 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.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 1963, 2365 ] }
54,345
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
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.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 3121, 3299 ] }
54,346
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
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.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 3524, 3724 ] }
54,347
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
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.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 4094, 4325 ] }
54,348
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
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"); // solhint-disable-next-line avoid-low-level-calls (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.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 4576, 5111 ] }
54,349
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
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.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 5291, 5495 ] }
54,350
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
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"); // solhint-disable-next-line avoid-low-level-calls (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.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 5682, 6109 ] }
54,351
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
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.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 6291, 6496 ] }
54,352
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionDelegateCall
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (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.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 6685, 7113 ] }
54,353
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
owner
function owner() public view virtual returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 497, 589 ] }
54,354
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
renounceOwnership
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 1148, 1301 ] }
54,355
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Ownable
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 1451, 1700 ] }
54,356
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Corgibutt
contract Corgibutt is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address constant public burnAddr = 0x000000000000000000000000000000000000dEaD; address constant public zeroAddr = address(0); mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**12; // 1Q uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Corgi Butt'; string private _symbol = unicode'CORGIB🍑'; uint8 private _decimals = 9; // Tax and team fees will start at 0 so we don't have a big impact when deploying to Uniswap // Team wallet address is null but the method to set the address is exposed uint256 private _taxFee = 2; uint256 private _burnFee = 1; uint256 private _teamFee = 3; uint256 private _previousTaxFee = _taxFee; uint256 private _previousBurnFee = _burnFee; uint256 private _previousTeamFee = _teamFee; address payable public _tWallet; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 500000000 * 10**4 * 10**18; // 5T uint256 private _numOfTokensToExchangeForTeam = 5 * 10**6; // 5M bool private isCooldownEnabled = true; mapping(address => uint256) private buycooldown; mapping(address => uint256) private sellcooldown; mapping(address => uint256) private firstsell; mapping(address => uint256) private sellnumber; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable tWallet) public { _tWallet = tWallet; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[tWallet] = true; emit Transfer(zeroAddr, _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _previousTeamFee = _teamFee; _taxFee = 0; _burnFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; _teamFee = _previousTeamFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != zeroAddr, "ERC20: approve from the zero address"); require(spender != zeroAddr, "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != zeroAddr, "ERC20: transfer from the zero address"); require(recipient != zeroAddr, "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); // Enforce the max transfer amount only if // - the sender/recipient is NOT the contract owner. // - the receipient is NOT the team wallet if(sender != owner() && recipient != owner() && recipient != _tWallet) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } // Require buyers to wait at least 30 seconds between transactions. if (isCooldownEnabled && sender == uniswapV2Pair && recipient != address(uniswapV2Router) && !_isExcluded[recipient]) { require(buycooldown[recipient] < block.timestamp); buycooldown[recipient] = block.timestamp + (30 seconds); } // If this is a sell transaction, index the sell number // and cooldown period. // // NOTE This just enforces cooldown, it does NOT enforce // higher fees. if (isCooldownEnabled && sender != uniswapV2Pair && sender != address(uniswapV2Router)) { require(sellcooldown[sender] < block.timestamp); if(firstsell[sender] + (1 days) < block.timestamp){ sellnumber[sender] = 0; } if (sellnumber[sender] == 0) { sellnumber[sender]++; firstsell[sender] = block.timestamp; sellcooldown[sender] = block.timestamp + (1 hours); } else if (sellnumber[sender] == 1) { sellnumber[sender]++; sellcooldown[sender] = block.timestamp + (2 hours); } else if (sellnumber[sender] == 2) { sellnumber[sender]++; sellcooldown[sender] = block.timestamp + (6 hours); } else if (sellnumber[sender] == 3) { sellnumber[sender]++; sellcooldown[sender] = firstsell[sender] + (1 days); } } // If the contract holds _enough_ tokens collected from the team fees, // then swap them for ETH and transfer to the wallet. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the team wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and team fee _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToTeam(uint256 amount) private { _tWallet.transfer(amount); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rBurn, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee, rBurn, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rBurn, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee, rBurn, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rBurn, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee, rBurn, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rBurn, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee, rBurn, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee, uint256 rBurn, uint256 tBurn) private { _rTotal = _rTotal.sub(rFee).sub(rBurn); _tFeeTotal = _tFeeTotal.add(tFee); _rOwned[burnAddr] = _rOwned[burnAddr].add(rBurn); _tOwned[burnAddr] = _tOwned[burnAddr].add(tBurn); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount) = _getRValues(tAmount, tFee, tBurn.mul(_getRate())); return (rAmount, rTransferAmount, tFee.mul(_getRate()), tBurn.mul(_getRate()), tTransferAmount, tFee, tBurn, tTeam); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = tAmount.mul(_taxFee).div(100); uint256 tBurn = tAmount.mul(_burnFee).div(100); uint256 tTeam = tAmount.mul(_teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn).sub(tTeam); return (tTransferAmount, tFee, tBurn, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 rBurn) private view returns (uint256, uint256) { uint256 currentRate = _getRate(); uint256 rAmount = tAmount.mul(currentRate); uint256 rTransferAmount = rAmount.sub(tFee.mul(currentRate)).sub(rBurn); return (rAmount, rTransferAmount); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25'); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _teamFee = teamFee; } function _setTeamWallet(address payable tWallet) external onlyOwner() { _tWallet = tWallet; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9'); _maxTxAmount = maxTxAmount; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.div(10**2).mul(maxTxPercent); } function setCooldown(bool onoff) external onlyOwner() { isCooldownEnabled = onoff; } }
manualSwap
function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); }
// We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much
LineComment
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 12467, 12628 ] }
54,357
Corgibutt
Corgibutt.sol
0x6996e4f505fd17385f0ecef5c38c675c01ede4b8
Solidity
Corgibutt
contract Corgibutt is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address constant public burnAddr = 0x000000000000000000000000000000000000dEaD; address constant public zeroAddr = address(0); mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**12; // 1Q uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Corgi Butt'; string private _symbol = unicode'CORGIB🍑'; uint8 private _decimals = 9; // Tax and team fees will start at 0 so we don't have a big impact when deploying to Uniswap // Team wallet address is null but the method to set the address is exposed uint256 private _taxFee = 2; uint256 private _burnFee = 1; uint256 private _teamFee = 3; uint256 private _previousTaxFee = _taxFee; uint256 private _previousBurnFee = _burnFee; uint256 private _previousTeamFee = _teamFee; address payable public _tWallet; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 500000000 * 10**4 * 10**18; // 5T uint256 private _numOfTokensToExchangeForTeam = 5 * 10**6; // 5M bool private isCooldownEnabled = true; mapping(address => uint256) private buycooldown; mapping(address => uint256) private sellcooldown; mapping(address => uint256) private firstsell; mapping(address => uint256) private sellnumber; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable tWallet) public { _tWallet = tWallet; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[tWallet] = true; emit Transfer(zeroAddr, _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _previousTeamFee = _teamFee; _taxFee = 0; _burnFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; _teamFee = _previousTeamFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != zeroAddr, "ERC20: approve from the zero address"); require(spender != zeroAddr, "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != zeroAddr, "ERC20: transfer from the zero address"); require(recipient != zeroAddr, "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); // Enforce the max transfer amount only if // - the sender/recipient is NOT the contract owner. // - the receipient is NOT the team wallet if(sender != owner() && recipient != owner() && recipient != _tWallet) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } // Require buyers to wait at least 30 seconds between transactions. if (isCooldownEnabled && sender == uniswapV2Pair && recipient != address(uniswapV2Router) && !_isExcluded[recipient]) { require(buycooldown[recipient] < block.timestamp); buycooldown[recipient] = block.timestamp + (30 seconds); } // If this is a sell transaction, index the sell number // and cooldown period. // // NOTE This just enforces cooldown, it does NOT enforce // higher fees. if (isCooldownEnabled && sender != uniswapV2Pair && sender != address(uniswapV2Router)) { require(sellcooldown[sender] < block.timestamp); if(firstsell[sender] + (1 days) < block.timestamp){ sellnumber[sender] = 0; } if (sellnumber[sender] == 0) { sellnumber[sender]++; firstsell[sender] = block.timestamp; sellcooldown[sender] = block.timestamp + (1 hours); } else if (sellnumber[sender] == 1) { sellnumber[sender]++; sellcooldown[sender] = block.timestamp + (2 hours); } else if (sellnumber[sender] == 2) { sellnumber[sender]++; sellcooldown[sender] = block.timestamp + (6 hours); } else if (sellnumber[sender] == 3) { sellnumber[sender]++; sellcooldown[sender] = firstsell[sender] + (1 days); } } // If the contract holds _enough_ tokens collected from the team fees, // then swap them for ETH and transfer to the wallet. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the team wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and team fee _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToTeam(uint256 amount) private { _tWallet.transfer(amount); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rBurn, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee, rBurn, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rBurn, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee, rBurn, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rBurn, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee, rBurn, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rBurn, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee, rBurn, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee, uint256 rBurn, uint256 tBurn) private { _rTotal = _rTotal.sub(rFee).sub(rBurn); _tFeeTotal = _tFeeTotal.add(tFee); _rOwned[burnAddr] = _rOwned[burnAddr].add(rBurn); _tOwned[burnAddr] = _tOwned[burnAddr].add(tBurn); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tTeam) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount) = _getRValues(tAmount, tFee, tBurn.mul(_getRate())); return (rAmount, rTransferAmount, tFee.mul(_getRate()), tBurn.mul(_getRate()), tTransferAmount, tFee, tBurn, tTeam); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = tAmount.mul(_taxFee).div(100); uint256 tBurn = tAmount.mul(_burnFee).div(100); uint256 tTeam = tAmount.mul(_teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn).sub(tTeam); return (tTransferAmount, tFee, tBurn, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 rBurn) private view returns (uint256, uint256) { uint256 currentRate = _getRate(); uint256 rAmount = tAmount.mul(currentRate); uint256 rTransferAmount = rAmount.sub(tFee.mul(currentRate)).sub(rBurn); return (rAmount, rTransferAmount); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25'); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _teamFee = teamFee; } function _setTeamWallet(address payable tWallet) external onlyOwner() { _tWallet = tWallet; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9'); _maxTxAmount = maxTxAmount; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.div(10**2).mul(maxTxPercent); } function setCooldown(bool onoff) external onlyOwner() { isCooldownEnabled = onoff; } }
//to recieve ETH from uniswapV2Router when swaping
LineComment
v0.8.4+commit.c7e474f2
Unlicense
ipfs://f9fe918dc56d63794085ed0266c56eec834b405f2a8807bb423678b7863d897b
{ "func_code_index": [ 16857, 16891 ] }
54,358
ERC20
Token.sol
0xb0a75239fe6046b756de135bd7c7233802c76d40
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://478c293d2fe1827a3491963026f890013ddadc6f4c378b46d52493dc37b40cef
{ "func_code_index": [ 90, 149 ] }
54,359
ERC20
Token.sol
0xb0a75239fe6046b756de135bd7c7233802c76d40
Solidity
IERC20
interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://478c293d2fe1827a3491963026f890013ddadc6f4c378b46d52493dc37b40cef
{ "func_code_index": [ 228, 300 ] }
54,360