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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
MultiSigWallet | MultiSigWallet.sol | 0x6d94b2dcdb49e671a39794124dd9361ca2ab3c68 | Solidity | MultiSigWallet | contract MultiSigWallet is AccessControl {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId, address indexed sender);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 3;
/*
* Storage
*/
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes public constant mintActionHash = abi.encodeWithSignature(
"mint(uint256)"
);
bytes public constant burnActionHash = abi.encodeWithSignature(
"burn(uint256)"
);
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
address sender;
uint256 timestamp;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT &&
_required <= ownerCount &&
_required != 0 &&
ownerCount != 0
);
_;
}
/// @dev Fallback function allows to deposit ether.
receive() external payable {
if (msg.value > 0) emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint256 _required)
public
validRequirement(_owners.length, _required)
{
_setupRole(DEFAULT_ADMIN_ROLE, address(this));
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
_setupRole(DEFAULT_ADMIN_ROLE, _owners[i]);
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
// function addOwner(address owner)
// public
// onlyWallet
// ownerDoesNotExist(owner)
// notNull(owner)
// validRequirement(owners.length + 1, required)
// {
// isOwner[owner] = true;
// owners.push(owner);
// _setupRole(DEFAULT_ADMIN_ROLE, owner);
// emit OwnerAddition(owner);
// }
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
// function removeOwner(address owner) public onlyWallet ownerExists(owner) {
// isOwner[owner] = false;
// for (uint256 i = 0; i < owners.length - 1; i++)
// if (owners[i] == owner) {
// owners[i] = owners[owners.length - 1];
// break;
// }
// owners.pop();
// if (required > owners.length) changeRequirement(owners.length);
// emit OwnerRemoval(owner);
// }
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
_revokeRole(DEFAULT_ADMIN_ROLE, owner);
isOwner[newOwner] = true;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
// function changeRequirement(uint256 _required)
// public
// onlyWallet
// validRequirement(owners.length, _required)
// {
// required = _required;
// emit RequirementChange(_required);
// }
/// @dev Allows an owner/admin, minter, burner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes memory data
) public ownerExists(msg.sender) returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function submitMintTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(MINTER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a minter or admin"
);
bytes memory actionHash = abi.encodePacked(mintActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function submitBurnTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(BURNER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a burner or admin"
);
bytes memory actionHash = abi.encodePacked(burnActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function grantRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
grantRole(_role, _account);
}
function revokeRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
revokeRole(_role, _account);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
external_call(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
sender: msg.sender,
timestamp: now
});
transactionCount += 1;
emit Submission(transactionId, msg.sender);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function renounceRole(bytes32 role, address account)
public
virtual
override
{
revert("Cannot renounceRole");
}
} | /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. | NatSpecSingleLine | external_call | function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
| // call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory. | LineComment | v0.6.2+commit.bacdbe57 | None | ipfs://57f8becce021d274ae37e2dbe1946dec534280eb4930d3398a27909b96ecd4be | {
"func_code_index": [
9781,
10899
]
} | 55,861 |
MultiSigWallet | MultiSigWallet.sol | 0x6d94b2dcdb49e671a39794124dd9361ca2ab3c68 | Solidity | MultiSigWallet | contract MultiSigWallet is AccessControl {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId, address indexed sender);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 3;
/*
* Storage
*/
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes public constant mintActionHash = abi.encodeWithSignature(
"mint(uint256)"
);
bytes public constant burnActionHash = abi.encodeWithSignature(
"burn(uint256)"
);
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
address sender;
uint256 timestamp;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT &&
_required <= ownerCount &&
_required != 0 &&
ownerCount != 0
);
_;
}
/// @dev Fallback function allows to deposit ether.
receive() external payable {
if (msg.value > 0) emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint256 _required)
public
validRequirement(_owners.length, _required)
{
_setupRole(DEFAULT_ADMIN_ROLE, address(this));
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
_setupRole(DEFAULT_ADMIN_ROLE, _owners[i]);
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
// function addOwner(address owner)
// public
// onlyWallet
// ownerDoesNotExist(owner)
// notNull(owner)
// validRequirement(owners.length + 1, required)
// {
// isOwner[owner] = true;
// owners.push(owner);
// _setupRole(DEFAULT_ADMIN_ROLE, owner);
// emit OwnerAddition(owner);
// }
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
// function removeOwner(address owner) public onlyWallet ownerExists(owner) {
// isOwner[owner] = false;
// for (uint256 i = 0; i < owners.length - 1; i++)
// if (owners[i] == owner) {
// owners[i] = owners[owners.length - 1];
// break;
// }
// owners.pop();
// if (required > owners.length) changeRequirement(owners.length);
// emit OwnerRemoval(owner);
// }
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
_revokeRole(DEFAULT_ADMIN_ROLE, owner);
isOwner[newOwner] = true;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
// function changeRequirement(uint256 _required)
// public
// onlyWallet
// validRequirement(owners.length, _required)
// {
// required = _required;
// emit RequirementChange(_required);
// }
/// @dev Allows an owner/admin, minter, burner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes memory data
) public ownerExists(msg.sender) returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function submitMintTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(MINTER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a minter or admin"
);
bytes memory actionHash = abi.encodePacked(mintActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function submitBurnTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(BURNER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a burner or admin"
);
bytes memory actionHash = abi.encodePacked(burnActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function grantRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
grantRole(_role, _account);
}
function revokeRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
revokeRole(_role, _account);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
external_call(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
sender: msg.sender,
timestamp: now
});
transactionCount += 1;
emit Submission(transactionId, msg.sender);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function renounceRole(bytes32 role, address account)
public
virtual
override
{
revert("Cannot renounceRole");
}
} | /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. | NatSpecSingleLine | isConfirmed | function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
| /// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status. | NatSpecSingleLine | v0.6.2+commit.bacdbe57 | None | ipfs://57f8becce021d274ae37e2dbe1946dec534280eb4930d3398a27909b96ecd4be | {
"func_code_index": [
11050,
11347
]
} | 55,862 |
MultiSigWallet | MultiSigWallet.sol | 0x6d94b2dcdb49e671a39794124dd9361ca2ab3c68 | Solidity | MultiSigWallet | contract MultiSigWallet is AccessControl {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId, address indexed sender);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 3;
/*
* Storage
*/
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes public constant mintActionHash = abi.encodeWithSignature(
"mint(uint256)"
);
bytes public constant burnActionHash = abi.encodeWithSignature(
"burn(uint256)"
);
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
address sender;
uint256 timestamp;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT &&
_required <= ownerCount &&
_required != 0 &&
ownerCount != 0
);
_;
}
/// @dev Fallback function allows to deposit ether.
receive() external payable {
if (msg.value > 0) emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint256 _required)
public
validRequirement(_owners.length, _required)
{
_setupRole(DEFAULT_ADMIN_ROLE, address(this));
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
_setupRole(DEFAULT_ADMIN_ROLE, _owners[i]);
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
// function addOwner(address owner)
// public
// onlyWallet
// ownerDoesNotExist(owner)
// notNull(owner)
// validRequirement(owners.length + 1, required)
// {
// isOwner[owner] = true;
// owners.push(owner);
// _setupRole(DEFAULT_ADMIN_ROLE, owner);
// emit OwnerAddition(owner);
// }
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
// function removeOwner(address owner) public onlyWallet ownerExists(owner) {
// isOwner[owner] = false;
// for (uint256 i = 0; i < owners.length - 1; i++)
// if (owners[i] == owner) {
// owners[i] = owners[owners.length - 1];
// break;
// }
// owners.pop();
// if (required > owners.length) changeRequirement(owners.length);
// emit OwnerRemoval(owner);
// }
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
_revokeRole(DEFAULT_ADMIN_ROLE, owner);
isOwner[newOwner] = true;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
// function changeRequirement(uint256 _required)
// public
// onlyWallet
// validRequirement(owners.length, _required)
// {
// required = _required;
// emit RequirementChange(_required);
// }
/// @dev Allows an owner/admin, minter, burner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes memory data
) public ownerExists(msg.sender) returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function submitMintTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(MINTER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a minter or admin"
);
bytes memory actionHash = abi.encodePacked(mintActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function submitBurnTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(BURNER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a burner or admin"
);
bytes memory actionHash = abi.encodePacked(burnActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function grantRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
grantRole(_role, _account);
}
function revokeRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
revokeRole(_role, _account);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
external_call(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
sender: msg.sender,
timestamp: now
});
transactionCount += 1;
emit Submission(transactionId, msg.sender);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function renounceRole(bytes32 role, address account)
public
virtual
override
{
revert("Cannot renounceRole");
}
} | /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. | NatSpecSingleLine | addTransaction | function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
sender: msg.sender,
timestamp: now
});
transactionCount += 1;
emit Submission(transactionId, msg.sender);
}
| /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID. | NatSpecSingleLine | v0.6.2+commit.bacdbe57 | None | ipfs://57f8becce021d274ae37e2dbe1946dec534280eb4930d3398a27909b96ecd4be | {
"func_code_index": [
11691,
12255
]
} | 55,863 |
MultiSigWallet | MultiSigWallet.sol | 0x6d94b2dcdb49e671a39794124dd9361ca2ab3c68 | Solidity | MultiSigWallet | contract MultiSigWallet is AccessControl {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId, address indexed sender);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 3;
/*
* Storage
*/
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes public constant mintActionHash = abi.encodeWithSignature(
"mint(uint256)"
);
bytes public constant burnActionHash = abi.encodeWithSignature(
"burn(uint256)"
);
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
address sender;
uint256 timestamp;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT &&
_required <= ownerCount &&
_required != 0 &&
ownerCount != 0
);
_;
}
/// @dev Fallback function allows to deposit ether.
receive() external payable {
if (msg.value > 0) emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint256 _required)
public
validRequirement(_owners.length, _required)
{
_setupRole(DEFAULT_ADMIN_ROLE, address(this));
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
_setupRole(DEFAULT_ADMIN_ROLE, _owners[i]);
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
// function addOwner(address owner)
// public
// onlyWallet
// ownerDoesNotExist(owner)
// notNull(owner)
// validRequirement(owners.length + 1, required)
// {
// isOwner[owner] = true;
// owners.push(owner);
// _setupRole(DEFAULT_ADMIN_ROLE, owner);
// emit OwnerAddition(owner);
// }
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
// function removeOwner(address owner) public onlyWallet ownerExists(owner) {
// isOwner[owner] = false;
// for (uint256 i = 0; i < owners.length - 1; i++)
// if (owners[i] == owner) {
// owners[i] = owners[owners.length - 1];
// break;
// }
// owners.pop();
// if (required > owners.length) changeRequirement(owners.length);
// emit OwnerRemoval(owner);
// }
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
_revokeRole(DEFAULT_ADMIN_ROLE, owner);
isOwner[newOwner] = true;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
// function changeRequirement(uint256 _required)
// public
// onlyWallet
// validRequirement(owners.length, _required)
// {
// required = _required;
// emit RequirementChange(_required);
// }
/// @dev Allows an owner/admin, minter, burner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes memory data
) public ownerExists(msg.sender) returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function submitMintTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(MINTER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a minter or admin"
);
bytes memory actionHash = abi.encodePacked(mintActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function submitBurnTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(BURNER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a burner or admin"
);
bytes memory actionHash = abi.encodePacked(burnActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function grantRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
grantRole(_role, _account);
}
function revokeRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
revokeRole(_role, _account);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
external_call(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
sender: msg.sender,
timestamp: now
});
transactionCount += 1;
emit Submission(transactionId, msg.sender);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function renounceRole(bytes32 role, address account)
public
virtual
override
{
revert("Cannot renounceRole");
}
} | /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. | NatSpecSingleLine | getConfirmationCount | function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
| /// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations. | NatSpecSingleLine | v0.6.2+commit.bacdbe57 | None | ipfs://57f8becce021d274ae37e2dbe1946dec534280eb4930d3398a27909b96ecd4be | {
"func_code_index": [
12461,
12718
]
} | 55,864 |
MultiSigWallet | MultiSigWallet.sol | 0x6d94b2dcdb49e671a39794124dd9361ca2ab3c68 | Solidity | MultiSigWallet | contract MultiSigWallet is AccessControl {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId, address indexed sender);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 3;
/*
* Storage
*/
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes public constant mintActionHash = abi.encodeWithSignature(
"mint(uint256)"
);
bytes public constant burnActionHash = abi.encodeWithSignature(
"burn(uint256)"
);
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
address sender;
uint256 timestamp;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT &&
_required <= ownerCount &&
_required != 0 &&
ownerCount != 0
);
_;
}
/// @dev Fallback function allows to deposit ether.
receive() external payable {
if (msg.value > 0) emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint256 _required)
public
validRequirement(_owners.length, _required)
{
_setupRole(DEFAULT_ADMIN_ROLE, address(this));
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
_setupRole(DEFAULT_ADMIN_ROLE, _owners[i]);
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
// function addOwner(address owner)
// public
// onlyWallet
// ownerDoesNotExist(owner)
// notNull(owner)
// validRequirement(owners.length + 1, required)
// {
// isOwner[owner] = true;
// owners.push(owner);
// _setupRole(DEFAULT_ADMIN_ROLE, owner);
// emit OwnerAddition(owner);
// }
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
// function removeOwner(address owner) public onlyWallet ownerExists(owner) {
// isOwner[owner] = false;
// for (uint256 i = 0; i < owners.length - 1; i++)
// if (owners[i] == owner) {
// owners[i] = owners[owners.length - 1];
// break;
// }
// owners.pop();
// if (required > owners.length) changeRequirement(owners.length);
// emit OwnerRemoval(owner);
// }
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
_revokeRole(DEFAULT_ADMIN_ROLE, owner);
isOwner[newOwner] = true;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
// function changeRequirement(uint256 _required)
// public
// onlyWallet
// validRequirement(owners.length, _required)
// {
// required = _required;
// emit RequirementChange(_required);
// }
/// @dev Allows an owner/admin, minter, burner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes memory data
) public ownerExists(msg.sender) returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function submitMintTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(MINTER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a minter or admin"
);
bytes memory actionHash = abi.encodePacked(mintActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function submitBurnTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(BURNER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a burner or admin"
);
bytes memory actionHash = abi.encodePacked(burnActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function grantRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
grantRole(_role, _account);
}
function revokeRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
revokeRole(_role, _account);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
external_call(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
sender: msg.sender,
timestamp: now
});
transactionCount += 1;
emit Submission(transactionId, msg.sender);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function renounceRole(bytes32 role, address account)
public
virtual
override
{
revert("Cannot renounceRole");
}
} | /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. | NatSpecSingleLine | getTransactionCount | function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
| /// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied. | NatSpecSingleLine | v0.6.2+commit.bacdbe57 | None | ipfs://57f8becce021d274ae37e2dbe1946dec534280eb4930d3398a27909b96ecd4be | {
"func_code_index": [
12987,
13342
]
} | 55,865 |
MultiSigWallet | MultiSigWallet.sol | 0x6d94b2dcdb49e671a39794124dd9361ca2ab3c68 | Solidity | MultiSigWallet | contract MultiSigWallet is AccessControl {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId, address indexed sender);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 3;
/*
* Storage
*/
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes public constant mintActionHash = abi.encodeWithSignature(
"mint(uint256)"
);
bytes public constant burnActionHash = abi.encodeWithSignature(
"burn(uint256)"
);
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
address sender;
uint256 timestamp;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT &&
_required <= ownerCount &&
_required != 0 &&
ownerCount != 0
);
_;
}
/// @dev Fallback function allows to deposit ether.
receive() external payable {
if (msg.value > 0) emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint256 _required)
public
validRequirement(_owners.length, _required)
{
_setupRole(DEFAULT_ADMIN_ROLE, address(this));
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
_setupRole(DEFAULT_ADMIN_ROLE, _owners[i]);
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
// function addOwner(address owner)
// public
// onlyWallet
// ownerDoesNotExist(owner)
// notNull(owner)
// validRequirement(owners.length + 1, required)
// {
// isOwner[owner] = true;
// owners.push(owner);
// _setupRole(DEFAULT_ADMIN_ROLE, owner);
// emit OwnerAddition(owner);
// }
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
// function removeOwner(address owner) public onlyWallet ownerExists(owner) {
// isOwner[owner] = false;
// for (uint256 i = 0; i < owners.length - 1; i++)
// if (owners[i] == owner) {
// owners[i] = owners[owners.length - 1];
// break;
// }
// owners.pop();
// if (required > owners.length) changeRequirement(owners.length);
// emit OwnerRemoval(owner);
// }
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
_revokeRole(DEFAULT_ADMIN_ROLE, owner);
isOwner[newOwner] = true;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
// function changeRequirement(uint256 _required)
// public
// onlyWallet
// validRequirement(owners.length, _required)
// {
// required = _required;
// emit RequirementChange(_required);
// }
/// @dev Allows an owner/admin, minter, burner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes memory data
) public ownerExists(msg.sender) returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function submitMintTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(MINTER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a minter or admin"
);
bytes memory actionHash = abi.encodePacked(mintActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function submitBurnTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(BURNER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a burner or admin"
);
bytes memory actionHash = abi.encodePacked(burnActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function grantRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
grantRole(_role, _account);
}
function revokeRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
revokeRole(_role, _account);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
external_call(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
sender: msg.sender,
timestamp: now
});
transactionCount += 1;
emit Submission(transactionId, msg.sender);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function renounceRole(bytes32 role, address account)
public
virtual
override
{
revert("Cannot renounceRole");
}
} | /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. | NatSpecSingleLine | getOwners | function getOwners() public view returns (address[] memory) {
return owners;
}
| /// @dev Returns list of owners.
/// @return List of owner addresses. | NatSpecSingleLine | v0.6.2+commit.bacdbe57 | None | ipfs://57f8becce021d274ae37e2dbe1946dec534280eb4930d3398a27909b96ecd4be | {
"func_code_index": [
13425,
13522
]
} | 55,866 |
MultiSigWallet | MultiSigWallet.sol | 0x6d94b2dcdb49e671a39794124dd9361ca2ab3c68 | Solidity | MultiSigWallet | contract MultiSigWallet is AccessControl {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId, address indexed sender);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 3;
/*
* Storage
*/
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes public constant mintActionHash = abi.encodeWithSignature(
"mint(uint256)"
);
bytes public constant burnActionHash = abi.encodeWithSignature(
"burn(uint256)"
);
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
address sender;
uint256 timestamp;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT &&
_required <= ownerCount &&
_required != 0 &&
ownerCount != 0
);
_;
}
/// @dev Fallback function allows to deposit ether.
receive() external payable {
if (msg.value > 0) emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint256 _required)
public
validRequirement(_owners.length, _required)
{
_setupRole(DEFAULT_ADMIN_ROLE, address(this));
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
_setupRole(DEFAULT_ADMIN_ROLE, _owners[i]);
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
// function addOwner(address owner)
// public
// onlyWallet
// ownerDoesNotExist(owner)
// notNull(owner)
// validRequirement(owners.length + 1, required)
// {
// isOwner[owner] = true;
// owners.push(owner);
// _setupRole(DEFAULT_ADMIN_ROLE, owner);
// emit OwnerAddition(owner);
// }
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
// function removeOwner(address owner) public onlyWallet ownerExists(owner) {
// isOwner[owner] = false;
// for (uint256 i = 0; i < owners.length - 1; i++)
// if (owners[i] == owner) {
// owners[i] = owners[owners.length - 1];
// break;
// }
// owners.pop();
// if (required > owners.length) changeRequirement(owners.length);
// emit OwnerRemoval(owner);
// }
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
_revokeRole(DEFAULT_ADMIN_ROLE, owner);
isOwner[newOwner] = true;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
// function changeRequirement(uint256 _required)
// public
// onlyWallet
// validRequirement(owners.length, _required)
// {
// required = _required;
// emit RequirementChange(_required);
// }
/// @dev Allows an owner/admin, minter, burner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes memory data
) public ownerExists(msg.sender) returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function submitMintTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(MINTER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a minter or admin"
);
bytes memory actionHash = abi.encodePacked(mintActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function submitBurnTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(BURNER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a burner or admin"
);
bytes memory actionHash = abi.encodePacked(burnActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function grantRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
grantRole(_role, _account);
}
function revokeRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
revokeRole(_role, _account);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
external_call(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
sender: msg.sender,
timestamp: now
});
transactionCount += 1;
emit Submission(transactionId, msg.sender);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function renounceRole(bytes32 role, address account)
public
virtual
override
{
revert("Cannot renounceRole");
}
} | /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. | NatSpecSingleLine | getConfirmations | function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
| /// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses. | NatSpecSingleLine | v0.6.2+commit.bacdbe57 | None | ipfs://57f8becce021d274ae37e2dbe1946dec534280eb4930d3398a27909b96ecd4be | {
"func_code_index": [
13716,
14319
]
} | 55,867 |
MultiSigWallet | MultiSigWallet.sol | 0x6d94b2dcdb49e671a39794124dd9361ca2ab3c68 | Solidity | MultiSigWallet | contract MultiSigWallet is AccessControl {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId, address indexed sender);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 3;
/*
* Storage
*/
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes public constant mintActionHash = abi.encodeWithSignature(
"mint(uint256)"
);
bytes public constant burnActionHash = abi.encodeWithSignature(
"burn(uint256)"
);
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
address sender;
uint256 timestamp;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT &&
_required <= ownerCount &&
_required != 0 &&
ownerCount != 0
);
_;
}
/// @dev Fallback function allows to deposit ether.
receive() external payable {
if (msg.value > 0) emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint256 _required)
public
validRequirement(_owners.length, _required)
{
_setupRole(DEFAULT_ADMIN_ROLE, address(this));
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
_setupRole(DEFAULT_ADMIN_ROLE, _owners[i]);
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
// function addOwner(address owner)
// public
// onlyWallet
// ownerDoesNotExist(owner)
// notNull(owner)
// validRequirement(owners.length + 1, required)
// {
// isOwner[owner] = true;
// owners.push(owner);
// _setupRole(DEFAULT_ADMIN_ROLE, owner);
// emit OwnerAddition(owner);
// }
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
// function removeOwner(address owner) public onlyWallet ownerExists(owner) {
// isOwner[owner] = false;
// for (uint256 i = 0; i < owners.length - 1; i++)
// if (owners[i] == owner) {
// owners[i] = owners[owners.length - 1];
// break;
// }
// owners.pop();
// if (required > owners.length) changeRequirement(owners.length);
// emit OwnerRemoval(owner);
// }
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
_revokeRole(DEFAULT_ADMIN_ROLE, owner);
isOwner[newOwner] = true;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
// function changeRequirement(uint256 _required)
// public
// onlyWallet
// validRequirement(owners.length, _required)
// {
// required = _required;
// emit RequirementChange(_required);
// }
/// @dev Allows an owner/admin, minter, burner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes memory data
) public ownerExists(msg.sender) returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function submitMintTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(MINTER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a minter or admin"
);
bytes memory actionHash = abi.encodePacked(mintActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function submitBurnTransaction(address destination, bytes memory data)
public
returns (uint256 transactionId)
{
require(
hasRole(BURNER_ROLE, msg.sender) || isOwner[msg.sender],
"Caller is not a burner or admin"
);
bytes memory actionHash = abi.encodePacked(burnActionHash, data);
transactionId = addTransaction(destination, 0, actionHash);
}
function grantRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
grantRole(_role, _account);
}
function revokeRoleTransaction(bytes32 _role, address _account)
public
onlyWallet
{
revokeRole(_role, _account);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
external_call(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false,
sender: msg.sender,
timestamp: now
});
transactionCount += 1;
emit Submission(transactionId, msg.sender);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function renounceRole(bytes32 role, address account)
public
virtual
override
{
revert("Cannot renounceRole");
}
} | /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. | NatSpecSingleLine | getTransactionIds | function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
| /// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs. | NatSpecSingleLine | v0.6.2+commit.bacdbe57 | None | ipfs://57f8becce021d274ae37e2dbe1946dec534280eb4930d3398a27909b96ecd4be | {
"func_code_index": [
14687,
15452
]
} | 55,868 |
ComponentToken | ./contracts/test/TestERC20.sol | 0x9f20ed5f919dc1c1695042542c13adcfc100dcab | Solidity | ComponentToken | contract ComponentToken is Context, AccessControlEnumerable, ERC20Burnable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE` and `MINTER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
} | /**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter
* role, as well as the default admin role, which will let it grant minter
* role to other accounts.
*/ | NatSpecMultiLine | mint | function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
| /**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/ | NatSpecMultiLine | v0.8.4+commit.c7e474f2 | MIT | ipfs://5d8c535da114c5c0a00f42dd7d5f28ae15a7cd114068e1659ce7c29ab3eb676d | {
"func_code_index": [
680,
886
]
} | 55,869 |
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | Ownable | function Ownable() public {
owner = msg.sender;
}
| /**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
261,
321
]
} | 55,870 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
640,
816
]
} | 55,871 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
| /**
* @dev Multiplies two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
89,
272
]
} | 55,872 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @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 c;
}
| /**
* @dev Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
356,
629
]
} | 55,873 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @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 Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
744,
860
]
} | 55,874 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
924,
1060
]
} | 55,875 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view returns (uint256) {
return totalSupply_;
}
| /**
* @dev total number of tokens in existence
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
199,
287
]
} | 55,876 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | transfer | function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| /**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
445,
836
]
} | 55,877 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
} | /**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
1042,
1154
]
} | 55,878 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
| /**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
401,
853
]
} | 55,879 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | approve | function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
1485,
1675
]
} | 55,880 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | allowance | function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
1999,
2130
]
} | 55,881 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | increaseApproval | function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
2596,
2860
]
} | 55,882 |
|
Presale | Presale.sol | 0x21847ee0c0518f21f15bbaccb38c40c6399c9b09 | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | decreaseApproval | function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/ | NatSpecMultiLine | v0.4.20+commit.3155dd80 | bzzr://1789ac16beac56c1b13168f9701387343ceee28d305a98f7fa181e4fa234d750 | {
"func_code_index": [
3331,
3741
]
} | 55,883 |
|
MiningCore | IERC1155TokenReceiver.sol | 0xb4747de7cc2f0a5f80a692d98a2b5e9089a485c8 | Solidity | IERC1155TokenReceiver | interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
/**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more than 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool);
} | /**
* @dev ERC-1155 interface for accepting safe transfers.
*/ | NatSpecMultiLine | onERC1155Received | function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4);
| /**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | None | ipfs://f7f2b0ce8f888229ab3d76b219a5bb987e42f3cf0d2e128ed746c795fc25358e | {
"func_code_index": [
946,
1086
]
} | 55,884 |
MiningCore | IERC1155TokenReceiver.sol | 0xb4747de7cc2f0a5f80a692d98a2b5e9089a485c8 | Solidity | IERC1155TokenReceiver | interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
/**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more than 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool);
} | /**
* @dev ERC-1155 interface for accepting safe transfers.
*/ | NatSpecMultiLine | onERC1155BatchReceived | function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
| /**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | None | ipfs://f7f2b0ce8f888229ab3d76b219a5bb987e42f3cf0d2e128ed746c795fc25358e | {
"func_code_index": [
2060,
2229
]
} | 55,885 |
MiningCore | IERC1155TokenReceiver.sol | 0xb4747de7cc2f0a5f80a692d98a2b5e9089a485c8 | Solidity | IERC1155TokenReceiver | interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
/**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more than 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool);
} | /**
* @dev ERC-1155 interface for accepting safe transfers.
*/ | NatSpecMultiLine | supportsInterface | function supportsInterface(bytes4 interfaceID) external view returns (bool);
| /**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more than 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | None | ipfs://f7f2b0ce8f888229ab3d76b219a5bb987e42f3cf0d2e128ed746c795fc25358e | {
"func_code_index": [
2708,
2786
]
} | 55,886 |
ERC721_Minimal | contracts/TheNothingERC721/MinimalERC721_V4_worm.sol | 0xda4a273b987424e20875aa7064c1c0d6f834546e | Solidity | Strings | library Strings { //from OpenZeppelin v4.4.1
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
} | toHexString | function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
| /**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/ | NatSpecMultiLine | v0.8.10+commit.fc410830 | MIT | ipfs://65b5bc3651aba31a0e871c9ec01816ea0eb2ab6b83f359a30fbae4521219d022 | {
"func_code_index": [
946,
1291
]
} | 55,887 |
||
ERC721_Minimal | contracts/TheNothingERC721/MinimalERC721_V4_worm.sol | 0xda4a273b987424e20875aa7064c1c0d6f834546e | Solidity | Strings | library Strings { //from OpenZeppelin v4.4.1
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
} | toHexString | function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
| /**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/ | NatSpecMultiLine | v0.8.10+commit.fc410830 | MIT | ipfs://65b5bc3651aba31a0e871c9ec01816ea0eb2ab6b83f359a30fbae4521219d022 | {
"func_code_index": [
1414,
1870
]
} | 55,888 |
||
ERC721_Minimal | contracts/TheNothingERC721/MinimalERC721_V4_worm.sol | 0xda4a273b987424e20875aa7064c1c0d6f834546e | Solidity | IERC721Receiver | interface IERC721Receiver {
/// returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns(bytes4);
} | onERC721Received | function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns(bytes4);
| /// returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` | NatSpecSingleLine | v0.8.10+commit.fc410830 | MIT | ipfs://65b5bc3651aba31a0e871c9ec01816ea0eb2ab6b83f359a30fbae4521219d022 | {
"func_code_index": [
117,
243
]
} | 55,889 |
||
ERC721_Minimal | contracts/TheNothingERC721/MinimalERC721_V4_worm.sol | 0xda4a273b987424e20875aa7064c1c0d6f834546e | Solidity | ITokenURICustom | interface ITokenURICustom {
// Implementation of a custom tokenURI
function constructTokenURI(uint256 tokenId) external pure returns (string memory);
} | constructTokenURI | function constructTokenURI(uint256 tokenId) external pure returns (string memory);
| // Implementation of a custom tokenURI | LineComment | v0.8.10+commit.fc410830 | MIT | ipfs://65b5bc3651aba31a0e871c9ec01816ea0eb2ab6b83f359a30fbae4521219d022 | {
"func_code_index": [
73,
160
]
} | 55,890 |
||
ERC721_Minimal | contracts/TheNothingERC721/MinimalERC721_V4_worm.sol | 0xda4a273b987424e20875aa7064c1c0d6f834546e | Solidity | ERC721_Minimal | contract ERC721_Minimal is Ownable{
using Strings for uint256;
//Events ERC721
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
//max supply before minting is disabled
//uint256 MAX_SUPPLY = type(uint160).max;
address burnAddress = 0x000000000000000000000000000000000000dEaD;
// Token name
string private _name;
// Token symbol
string private _symbol;
// string private baseURI;
// Optional mapping for token URIs
// mapping(uint256 => string) private _tokenURIs;
address private _customURI;
bool public finalised;
// Mapping from token ID to owner address
address[] private _owners;
uint256 public supplyCounter;
// Mapping owner address to token owner flag
mapping(address => bool) private _isOwner;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
// ERC-2981: NFT Royalty Standard
address payable private _royaltyRecipient;
uint256 private _royaltyBps;
constructor(string memory name_, string memory symbol_, address contractURI) {
_name = name_;
_symbol = symbol_;
//_setBaseURI(baseURI_);
_customURI = contractURI;
_royaltyRecipient = payable(msg.sender);
_royaltyBps = 1000;
_mint(msg.sender, supplyCounter);
supplyCounter+=1;
}
function setCustomURI(address contractURI) public onlyOwner {
require(finalised == false, "Uri finalised");
_customURI = contractURI;
}
function setFinalised() public onlyOwner {
finalised = true;
}
function supportsInterface(bytes4 interfaceId) public pure returns (bool) {
// return interfaceId == type(IERC165).interfaceId;
return interfaceId == 0x01ffc9a7 || interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f || interfaceId == 0x2a55205a;
//ERC721 = 0x80ac58cd
//ERC721 metadata = 0x5b5e139f
//ERC721 enumerabe = 0x780e9d63
//ERC721 receiver = 0x150b7a02
//ERC165 = 0x01ffc9a7b
//_INTERFACE_ID_ERC2981 = 0x2a55205a;
}
function totalSupply() public view returns (uint256)
{
return supplyCounter;
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
if(_isOwner[owner]) {
return 1;
}
else {
return 0;
}
}
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if(_customURI != address(0)) {
return ITokenURICustom(_customURI).constructTokenURI(tokenId);
}
else {
// string memory bURI = baseURI;
// return bytes(bURI).length > 0 ? string(abi.encodePacked(bURI, tokenId.toString())) : "";
return "Missing URI";
}
}
// function _setBaseURI(string memory baseURI_) internal {
// baseURI = baseURI_;
// }
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public {
_setApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < _owners.length && _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_owners.push(to);
_isOwner[to] = true;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal {
address owner = ownerOf(tokenId);
// Clear approvals
_approve(address(0), tokenId);
_isOwner[owner] = false;
_owners[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
require(!_isOwner[to], "ERC721: Only one token per wallet allowed");
if(balanceOf(burnAddress) > 0 || to == burnAddress) {
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId] = to;
_isOwner[to] = true;
_isOwner[from] = false;
emit Transfer(from, to, tokenId);
}
else {
_mint(to, supplyCounter);
supplyCounter+=1;
}
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
//EIP-2981 Royalty Standard
function setRoyaltyPercentageBasisPoints(uint256 royaltyPercentageBasisPoints) public onlyOwner {
_royaltyBps = royaltyPercentageBasisPoints;
}
function setRoyaltyReceipientAddress(address payable royaltyReceipientAddress) public onlyOwner {
_royaltyRecipient = royaltyReceipientAddress;
}
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {
uint256 royalty = (salePrice * _royaltyBps) / 10000;
return (_royaltyRecipient, royalty);
}
} | approve | function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
| // function _setBaseURI(string memory baseURI_) internal {
// baseURI = baseURI_;
// } | LineComment | v0.8.10+commit.fc410830 | MIT | ipfs://65b5bc3651aba31a0e871c9ec01816ea0eb2ab6b83f359a30fbae4521219d022 | {
"func_code_index": [
3936,
4325
]
} | 55,891 |
||
ERC721_Minimal | contracts/TheNothingERC721/MinimalERC721_V4_worm.sol | 0xda4a273b987424e20875aa7064c1c0d6f834546e | Solidity | ERC721_Minimal | contract ERC721_Minimal is Ownable{
using Strings for uint256;
//Events ERC721
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
//max supply before minting is disabled
//uint256 MAX_SUPPLY = type(uint160).max;
address burnAddress = 0x000000000000000000000000000000000000dEaD;
// Token name
string private _name;
// Token symbol
string private _symbol;
// string private baseURI;
// Optional mapping for token URIs
// mapping(uint256 => string) private _tokenURIs;
address private _customURI;
bool public finalised;
// Mapping from token ID to owner address
address[] private _owners;
uint256 public supplyCounter;
// Mapping owner address to token owner flag
mapping(address => bool) private _isOwner;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
// ERC-2981: NFT Royalty Standard
address payable private _royaltyRecipient;
uint256 private _royaltyBps;
constructor(string memory name_, string memory symbol_, address contractURI) {
_name = name_;
_symbol = symbol_;
//_setBaseURI(baseURI_);
_customURI = contractURI;
_royaltyRecipient = payable(msg.sender);
_royaltyBps = 1000;
_mint(msg.sender, supplyCounter);
supplyCounter+=1;
}
function setCustomURI(address contractURI) public onlyOwner {
require(finalised == false, "Uri finalised");
_customURI = contractURI;
}
function setFinalised() public onlyOwner {
finalised = true;
}
function supportsInterface(bytes4 interfaceId) public pure returns (bool) {
// return interfaceId == type(IERC165).interfaceId;
return interfaceId == 0x01ffc9a7 || interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f || interfaceId == 0x2a55205a;
//ERC721 = 0x80ac58cd
//ERC721 metadata = 0x5b5e139f
//ERC721 enumerabe = 0x780e9d63
//ERC721 receiver = 0x150b7a02
//ERC165 = 0x01ffc9a7b
//_INTERFACE_ID_ERC2981 = 0x2a55205a;
}
function totalSupply() public view returns (uint256)
{
return supplyCounter;
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
if(_isOwner[owner]) {
return 1;
}
else {
return 0;
}
}
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if(_customURI != address(0)) {
return ITokenURICustom(_customURI).constructTokenURI(tokenId);
}
else {
// string memory bURI = baseURI;
// return bytes(bURI).length > 0 ? string(abi.encodePacked(bURI, tokenId.toString())) : "";
return "Missing URI";
}
}
// function _setBaseURI(string memory baseURI_) internal {
// baseURI = baseURI_;
// }
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public {
_setApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < _owners.length && _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_owners.push(to);
_isOwner[to] = true;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal {
address owner = ownerOf(tokenId);
// Clear approvals
_approve(address(0), tokenId);
_isOwner[owner] = false;
_owners[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
require(!_isOwner[to], "ERC721: Only one token per wallet allowed");
if(balanceOf(burnAddress) > 0 || to == burnAddress) {
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId] = to;
_isOwner[to] = true;
_isOwner[from] = false;
emit Transfer(from, to, tokenId);
}
else {
_mint(to, supplyCounter);
supplyCounter+=1;
}
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
//EIP-2981 Royalty Standard
function setRoyaltyPercentageBasisPoints(uint256 royaltyPercentageBasisPoints) public onlyOwner {
_royaltyBps = royaltyPercentageBasisPoints;
}
function setRoyaltyReceipientAddress(address payable royaltyReceipientAddress) public onlyOwner {
_royaltyRecipient = royaltyReceipientAddress;
}
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {
uint256 royalty = (salePrice * _royaltyBps) / 10000;
return (_royaltyRecipient, royalty);
}
} | setRoyaltyPercentageBasisPoints | function setRoyaltyPercentageBasisPoints(uint256 royaltyPercentageBasisPoints) public onlyOwner {
_royaltyBps = royaltyPercentageBasisPoints;
}
| //EIP-2981 Royalty Standard | LineComment | v0.8.10+commit.fc410830 | MIT | ipfs://65b5bc3651aba31a0e871c9ec01816ea0eb2ab6b83f359a30fbae4521219d022 | {
"func_code_index": [
9284,
9446
]
} | 55,892 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | addPool | function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
| // Add a new lp to the pool. Can only be called by the owner. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
2412,
2972
]
} | 55,893 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | setTreasury | function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
| // Update treasury address by the previous treasury. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
3031,
3173
]
} | 55,894 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | setTreasuryFee | function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
| // Update treasury fee, capped at 10%. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
3218,
3395
]
} | 55,895 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | setPoolAlloc | function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
| // Update the allocation points of a specific pool | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
3452,
3780
]
} | 55,896 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | pendingStonk | function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
| // View function to see pending STONKs on frontend. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
3838,
4859
]
} | 55,897 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | totalPendingStonk | function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
| // View function to calculate the total pending STONKs of address across all pools | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
4948,
5224
]
} | 55,898 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | massUpdatePools | function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
| // Update reward variables for all pools. Be careful of gas spending! | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
5300,
5465
]
} | 55,899 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | updatePool | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
| // Update reward variables of the given pool to be up-to-date. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
5534,
6489
]
} | 55,900 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | deposit | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| // Deposit LP tokens to StonkMarketMaker for STONK allocation. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
6999,
7563
]
} | 55,901 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | withdraw | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| // Withdraw LP tokens from StonkMarketMaker. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
7614,
8150
]
} | 55,902 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | emergencyWithdraw | function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
| // Withdraw without caring about rewards. EMERGENCY ONLY. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
8214,
8578
]
} | 55,903 |
||
StonkMarketMaker | contracts\StonkMarketMaker.sol | 0x8dc182c4a2ac893e6071ff50097de0c96a5a42f8 | Solidity | StonkMarketMaker | contract StonkMarketMaker is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of STONKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accStonkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accStonkPerShare`, (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STONKs to distribute per block.
uint256 lastRewardBlock; // Last block number that STONKs distribution occurs.
uint256 accStonkPerShare; // Accumulated STONK rewards per share, times 1e12. See below.
}
StonkERC20 public stonk;
address public treasury;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => uint256) public tokenPID;
uint256 public totalAllocPoint = 0;
uint256 public treasuryFee = 1000;
uint256 public stonkPerBlock;
uint256 public rewardsStartBlock;
uint256 public rewardsEndBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
StonkERC20 _stonk,
address _treasury,
uint256 _rewardsEndBlock,
uint256 _totalStonkRewards
) public {
stonk = _stonk;
treasury = _treasury;
rewardsEndBlock = _rewardsEndBlock;
rewardsStartBlock = block.number;
stonkPerBlock = _totalStonkRewards.div(
rewardsEndBlock.sub(rewardsStartBlock)
);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(tokenPID[address(_lpToken)] == 0, 'addPool: Duplicate token pool.');
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: block.number,
accStonkPerShare: 0
})
);
tokenPID[address(_lpToken)] = poolInfo.length;
}
// Update treasury address by the previous treasury.
function setTreasury(address _treasury) public {
require(msg.sender == treasury, 'setTreasury: wut?');
treasury = _treasury;
}
// Update treasury fee, capped at 10%.
function setTreasuryFee(uint256 _treasuryFee) external onlyOwner {
require(_treasuryFee <= 1000, 'setTreasuryFee: max fee is 10%');
treasuryFee = _treasuryFee;
}
// Update the allocation points of a specific pool
function setPoolAlloc(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// View function to see pending STONKs on frontend.
function pendingStonk(uint256 _pid, address _user)
public
view
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
uint256 accStonkPerShare = pool.accStonkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
accStonkPerShare = accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accStonkPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to calculate the total pending STONKs of address across all pools
function totalPendingStonk(address _user) public view returns (uint256) {
uint256 total = 0;
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
total = total.add(pendingStonk(pid, _user));
}
return total;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 blockNumber = block.number < rewardsEndBlock
? block.number
: rewardsEndBlock;
if (blockNumber <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = blockNumber;
return;
}
uint256 multiplier = blockNumber.sub(pool.lastRewardBlock);
uint256 stonkReward = multiplier
.mul(stonkPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
uint256 treasuryReward = stonkReward.mul(treasuryFee).div(10000);
uint256 poolReward = stonkReward.sub(treasuryReward);
safeStonkTransfer(treasury, treasuryReward);
pool.accStonkPerShare = pool.accStonkPerShare.add(
poolReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = blockNumber;
}
function transferPendingRewards(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accStonkPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
if (pending > 0) {
safeStonkTransfer(msg.sender, pending);
}
}
// Deposit LP tokens to StonkMarketMaker for STONK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
transferPendingRewards(_pid);
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from StonkMarketMaker.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: not good');
transferPendingRewards(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accStonkPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs.
function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
} | safeStonkTransfer | function safeStonkTransfer(address _to, uint256 _amount) internal {
uint256 stonkBal = stonk.balanceOf(address(this));
if (_amount > stonkBal) {
stonk.transfer(_to, stonkBal);
} else {
stonk.transfer(_to, _amount);
}
}
| // Safe stonk transfer function, just in case if rounding error causes pool to not have enough STONKs. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://6e4db08fe41affe1f0cc72eb85ace437ea7979bad4af4bb0419d0ecaeac0800b | {
"func_code_index": [
8687,
8947
]
} | 55,904 |
||
GenesisMiners | contracts/GenesisMiners.sol | 0xf51692e1b605559b736d73722b8d8dbbacbdf028 | Solidity | GenesisMiners | contract GenesisMiners is ERC721, Pausable, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
string private _metadataBaseURI;
uint256 private _maxSupply;
uint256 private _maxMint;
uint256 private _price = 0.05 ether;
uint256 private _reserved = 7;
bool private _presale = true;
mapping(address => uint8) private _whitelist;
constructor(uint256 maxSupply, uint256 maxMint, string memory metadataBaseURI) ERC721("Miners Genesis", "MINER") {
_metadataBaseURI = metadataBaseURI;
_maxSupply = maxSupply;
_maxMint = maxMint;
}
function mintedCount() external view returns (uint256 supply) {
return _tokenIdCounter.current();
}
function reservedCount() external view returns (uint256 count) {
return _reserved;
}
function _baseURI() internal view override returns (string memory) {
return _metadataBaseURI;
}
function setBaseURI(string memory uri) external onlyOwner {
_metadataBaseURI = uri;
}
// Pausing
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, tokenId);
}
function getPrice() public view returns (uint256) {
return _price;
}
/** For if ETH price goes wack */
function setPrice(uint256 newPrice) public onlyOwner {
_price = newPrice;
}
function setReserved(uint256 newReserved) external onlyOwner {
_reserved = newReserved;
}
function bulkWhitelist(address[] memory addrs) external onlyOwner {
for (uint256 i = 0; i < addrs.length; i++) {
_whitelist[addrs[i]] = 1;
}
}
function startPublicSale() external onlyOwner {
_presale = false;
}
function mintAMiner() external payable {
require(msg.value >= _price, 'Ether sent not correct');
if (_presale) {
require(_whitelist[msg.sender] == 1, 'Not on list or already minted.');
_whitelist[msg.sender] = 0;
}
uint256 tokenId = _tokenIdCounter.current();
require(tokenId < _maxSupply - _reserved, 'Sold Out');
require(balanceOf(msg.sender) < _maxMint, 'Exceeded max mint per account');
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
function giveAwayMiner(address to) external onlyOwner {
require(_reserved > 0, 'Exceeds reserved supply');
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_reserved--;
}
function withdrawAll() external payable onlyOwner {
uint256 _amount = address(this).balance;
(bool success1, ) = payable(owner()).call{value: _amount}("");
require(success1, "Failed to send Ether to owner");
}
} | pause | function pause() public onlyOwner {
_pause();
}
| // Pausing | LineComment | v0.8.0+commit.c7dfd78e | {
"func_code_index": [
1019,
1074
]
} | 55,905 |
||||
GenesisMiners | contracts/GenesisMiners.sol | 0xf51692e1b605559b736d73722b8d8dbbacbdf028 | Solidity | GenesisMiners | contract GenesisMiners is ERC721, Pausable, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
string private _metadataBaseURI;
uint256 private _maxSupply;
uint256 private _maxMint;
uint256 private _price = 0.05 ether;
uint256 private _reserved = 7;
bool private _presale = true;
mapping(address => uint8) private _whitelist;
constructor(uint256 maxSupply, uint256 maxMint, string memory metadataBaseURI) ERC721("Miners Genesis", "MINER") {
_metadataBaseURI = metadataBaseURI;
_maxSupply = maxSupply;
_maxMint = maxMint;
}
function mintedCount() external view returns (uint256 supply) {
return _tokenIdCounter.current();
}
function reservedCount() external view returns (uint256 count) {
return _reserved;
}
function _baseURI() internal view override returns (string memory) {
return _metadataBaseURI;
}
function setBaseURI(string memory uri) external onlyOwner {
_metadataBaseURI = uri;
}
// Pausing
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, tokenId);
}
function getPrice() public view returns (uint256) {
return _price;
}
/** For if ETH price goes wack */
function setPrice(uint256 newPrice) public onlyOwner {
_price = newPrice;
}
function setReserved(uint256 newReserved) external onlyOwner {
_reserved = newReserved;
}
function bulkWhitelist(address[] memory addrs) external onlyOwner {
for (uint256 i = 0; i < addrs.length; i++) {
_whitelist[addrs[i]] = 1;
}
}
function startPublicSale() external onlyOwner {
_presale = false;
}
function mintAMiner() external payable {
require(msg.value >= _price, 'Ether sent not correct');
if (_presale) {
require(_whitelist[msg.sender] == 1, 'Not on list or already minted.');
_whitelist[msg.sender] = 0;
}
uint256 tokenId = _tokenIdCounter.current();
require(tokenId < _maxSupply - _reserved, 'Sold Out');
require(balanceOf(msg.sender) < _maxMint, 'Exceeded max mint per account');
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
function giveAwayMiner(address to) external onlyOwner {
require(_reserved > 0, 'Exceeds reserved supply');
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_reserved--;
}
function withdrawAll() external payable onlyOwner {
uint256 _amount = address(this).balance;
(bool success1, ) = payable(owner()).call{value: _amount}("");
require(success1, "Failed to send Ether to owner");
}
} | setPrice | function setPrice(uint256 newPrice) public onlyOwner {
_price = newPrice;
}
| /** For if ETH price goes wack */ | NatSpecMultiLine | v0.8.0+commit.c7dfd78e | {
"func_code_index": [
1430,
1513
]
} | 55,906 |
||||
MitchellGanondorfYoshiFalafelToken | MitchellGanondorfYoshiFalafelToken.sol | 0x1d31d3f85d2b5d55cdbf121d2583a42942c067c4 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | totalSupply | function totalSupply() constant returns (uint256 supply) {}
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.13+commit.0fb4cb1a | None | bzzr://436e368b1428cebe6b2ec6cab3e7fd9223f8a40f88e230ff6c2c8927be66f19a | {
"func_code_index": [
60,
124
]
} | 55,907 |
||
MitchellGanondorfYoshiFalafelToken | MitchellGanondorfYoshiFalafelToken.sol | 0x1d31d3f85d2b5d55cdbf121d2583a42942c067c4 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance) {}
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.13+commit.0fb4cb1a | None | bzzr://436e368b1428cebe6b2ec6cab3e7fd9223f8a40f88e230ff6c2c8927be66f19a | {
"func_code_index": [
232,
309
]
} | 55,908 |
||
MitchellGanondorfYoshiFalafelToken | MitchellGanondorfYoshiFalafelToken.sol | 0x1d31d3f85d2b5d55cdbf121d2583a42942c067c4 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.13+commit.0fb4cb1a | None | bzzr://436e368b1428cebe6b2ec6cab3e7fd9223f8a40f88e230ff6c2c8927be66f19a | {
"func_code_index": [
546,
623
]
} | 55,909 |
||
MitchellGanondorfYoshiFalafelToken | MitchellGanondorfYoshiFalafelToken.sol | 0x1d31d3f85d2b5d55cdbf121d2583a42942c067c4 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.13+commit.0fb4cb1a | None | bzzr://436e368b1428cebe6b2ec6cab3e7fd9223f8a40f88e230ff6c2c8927be66f19a | {
"func_code_index": [
946,
1042
]
} | 55,910 |
||
MitchellGanondorfYoshiFalafelToken | MitchellGanondorfYoshiFalafelToken.sol | 0x1d31d3f85d2b5d55cdbf121d2583a42942c067c4 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) returns (bool success) {}
| /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.13+commit.0fb4cb1a | None | bzzr://436e368b1428cebe6b2ec6cab3e7fd9223f8a40f88e230ff6c2c8927be66f19a | {
"func_code_index": [
1326,
1407
]
} | 55,911 |
||
MitchellGanondorfYoshiFalafelToken | MitchellGanondorfYoshiFalafelToken.sol | 0x1d31d3f85d2b5d55cdbf121d2583a42942c067c4 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
| /// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent | NatSpecSingleLine | v0.4.13+commit.0fb4cb1a | None | bzzr://436e368b1428cebe6b2ec6cab3e7fd9223f8a40f88e230ff6c2c8927be66f19a | {
"func_code_index": [
1615,
1712
]
} | 55,912 |
||
MitchellGanondorfYoshiFalafelToken | MitchellGanondorfYoshiFalafelToken.sol | 0x1d31d3f85d2b5d55cdbf121d2583a42942c067c4 | Solidity | MitchellGanondorfYoshiFalafelToken | contract MitchellGanondorfYoshiFalafelToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function MitchellGanondorfYoshiFalafelToken(
) {
balances[msg.sender] = 10; // Give the creator all initial tokens (100000 for example)
totalSupply = 10; // Update total supply (100000 for example)
name = "Mitchell Ganondorf Yoshi Falafel Token"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "MITCH"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | //name this contract whatever you'd like | LineComment | MitchellGanondorfYoshiFalafelToken | function MitchellGanondorfYoshiFalafelToken(
) {
balances[msg.sender] = 10; // Give the creator all initial tokens (100000 for example)
totalSupply = 10; // Update total supply (100000 for example)
name = "Mitchell Ganondorf Yoshi Falafel Token"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "MITCH"; // Set the symbol for display purposes
}
| //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token | LineComment | v0.4.13+commit.0fb4cb1a | None | bzzr://436e368b1428cebe6b2ec6cab3e7fd9223f8a40f88e230ff6c2c8927be66f19a | {
"func_code_index": [
1183,
1774
]
} | 55,913 |
MitchellGanondorfYoshiFalafelToken | MitchellGanondorfYoshiFalafelToken.sol | 0x1d31d3f85d2b5d55cdbf121d2583a42942c067c4 | Solidity | MitchellGanondorfYoshiFalafelToken | contract MitchellGanondorfYoshiFalafelToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function MitchellGanondorfYoshiFalafelToken(
) {
balances[msg.sender] = 10; // Give the creator all initial tokens (100000 for example)
totalSupply = 10; // Update total supply (100000 for example)
name = "Mitchell Ganondorf Yoshi Falafel Token"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "MITCH"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | //name this contract whatever you'd like | LineComment | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
| /* Approves and then calls the receiving contract */ | Comment | v0.4.13+commit.0fb4cb1a | None | bzzr://436e368b1428cebe6b2ec6cab3e7fd9223f8a40f88e230ff6c2c8927be66f19a | {
"func_code_index": [
1835,
2640
]
} | 55,914 |
GnosisProtocolRelayer | contracts/GnosisProtocolRelayer.sol | 0x30aad48f5ea5e8b2277612eb2a375fc173bb049e | Solidity | GnosisProtocolRelayer | contract GnosisProtocolRelayer {
using SafeMath for uint256;
event NewOrder(
uint256 indexed _orderIndex
);
event PlacedTrade(
uint256 indexed _orderIndex,
uint256 _gpOrderID
);
event WithdrawnExpiredOrder(
uint256 indexed _orderIndex
);
struct Order {
address tokenIn;
address tokenOut;
uint128 tokenInAmount;
uint128 tokenOutAmount;
uint256 priceTolerance;
uint256 minReserve;
address oraclePair;
uint256 deadline;
uint256 oracleId;
uint256 gpOrderId;
address factory;
bool executed;
}
uint256 public immutable GAS_ORACLE_UPDATE = 168364;
uint256 public immutable PARTS_PER_MILLION = 1000000;
uint256 public immutable BOUNTY = 0.01 ether; // To be decided
uint256 public immutable ORACLE_WINDOW_TIME = 120; // 2 Minutes
uint32 public immutable BATCH_TIME;
uint32 public immutable UINT32_MAX_VALUE = 2**32 - 1;
uint128 public immutable UINT128_MAX_VALUE = 2**128 - 1;
address public immutable batchExchange;
address public immutable epochTokenLocker;
address payable public immutable owner;
address public immutable WETH;
OracleCreator public oracleCreator;
uint256 public orderCount;
mapping(uint256 => Order) public orders;
mapping(address => bool) public exchangeFactoryWhitelist;
constructor(
address payable _owner,
address _batchExchange,
address _epochTokenLocker,
address[] memory _factoryWhitelist,
address _WETH,
OracleCreator _oracleCreater
) public {
require(_factoryWhitelist.length > 0, 'GnosisProtocolRelayer: MISSING_FACTORY_WHITELIST');
batchExchange = _batchExchange;
epochTokenLocker = _epochTokenLocker;
oracleCreator = _oracleCreater;
owner = _owner;
WETH = _WETH;
BATCH_TIME = IEpochTokenLocker(_epochTokenLocker).BATCH_TIME();
for (uint i=0; i < _factoryWhitelist.length; i++) {
exchangeFactoryWhitelist[_factoryWhitelist[i]] = true;
}
}
function orderTrade(
address tokenIn,
address tokenOut,
uint128 tokenInAmount,
uint128 tokenOutAmount,
uint256 priceTolerance,
uint256 minReserve,
uint256 deadline,
address factory
) external payable returns (uint256 orderIndex) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(tokenIn != tokenOut, 'GnosisProtocolRelayer: INVALID_PAIR');
require(tokenInAmount > 0 && tokenOutAmount > 0, 'GnosisProtocolRelayer: INVALID_TOKEN_AMOUNT');
require(priceTolerance <= PARTS_PER_MILLION, 'GnosisProtocolRelayer: INVALID_TOLERANCE');
require(deadline <= UINT32_MAX_VALUE, 'GnosisProtocolRelayer: INVALID_DEADLINE');
require(block.timestamp <= deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
if (tokenIn == address(0)) {
require(msg.value >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_ETH');
tokenIn = WETH;
IWETH(WETH).deposit{value: tokenInAmount}();
} else if (tokenOut == address(0)) {
tokenOut = WETH;
}
require(IERC20(tokenIn).balanceOf(address(this)) >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_TOKEN_IN');
address pair = _pair(tokenIn, tokenOut, factory);
require(pair != address(0), 'GnosisProtocolRelayer: UNKOWN_PAIR');
orderIndex = _OrderIndex();
orders[orderIndex] = Order({
tokenIn: tokenIn,
tokenOut: tokenOut,
tokenInAmount: tokenInAmount,
tokenOutAmount: tokenOutAmount,
priceTolerance: priceTolerance,
minReserve: minReserve,
oraclePair: pair,
deadline: deadline,
oracleId: 0,
gpOrderId: 0,
factory: factory,
executed: false
});
/* Create an oracle to calculate average price */
orders[orderIndex].oracleId = oracleCreator.createOracle(ORACLE_WINDOW_TIME, pair);
emit NewOrder(orderIndex);
}
function placeTrade(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
require(oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_RUNNING');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
order.executed = true;
/* Approve token on Gnosis Protocol */
TransferHelper.safeApprove(order.tokenIn, epochTokenLocker, order.tokenInAmount);
/* Deposit token in Gnosis Protocol */
IEpochTokenLocker(epochTokenLocker).deposit(order.tokenIn, order.tokenInAmount);
/* Lookup TokenIds in Gnosis Protocol */
uint16 sellToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenIn);
uint16 buyToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenOut);
uint256 expectedAmount = oracleCreator.consult(
order.oracleId,
order.tokenIn == address(0) ? WETH : order.tokenIn,
order.tokenInAmount
);
uint256 expectedAmountMin = expectedAmount.sub(expectedAmount.mul(order.priceTolerance) / PARTS_PER_MILLION);
uint256 expectedTokenOutAmount = order.tokenOutAmount;
require(
expectedAmountMin >= expectedTokenOutAmount.sub(expectedTokenOutAmount.mul(order.priceTolerance) / PARTS_PER_MILLION),
'GnosisProtocolRelayer: INVALID_PRICE_RANGE'
);
require(expectedAmountMin <= UINT128_MAX_VALUE,'GnosisProtocolRelayer: AMOUNT_OUT_OF_RANGE');
/* Calculate batch Deadline (5 Minutes window) */
uint32 validUntil = uint32(order.deadline/BATCH_TIME);
uint256 gpOrderId = IBatchExchange(batchExchange).placeOrder(buyToken, sellToken, validUntil, uint128(expectedAmountMin), order.tokenInAmount);
order.gpOrderId = gpOrderId;
emit PlacedTrade(orderIndex, gpOrderId);
}
function cancelOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(order.executed, 'GnosisProtocolRelayer: ORDER_NOT_EXECUTED');
uint16[] memory orderArray = new uint16[](1);
orderArray[0] = uint16(order.gpOrderId);
IBatchExchange(batchExchange).cancelOrders(orderArray);
}
// Updates a price oracle and sends a bounty to msg.sender
function updateOracle(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(!oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_ENDED');
uint256 amountBounty = GAS_ORACLE_UPDATE.mul(tx.gasprice).add(BOUNTY);
(uint reserve0, uint reserve1,) = IDXswapPair(order.oraclePair).getReserves();
address token0 = IDXswapPair(order.oraclePair).token0();
address tokenIn = order.tokenIn == address(0) ? WETH : order.tokenIn;
// Makes sure the reserve of TokenIn is higher then minReserve
if(tokenIn == token0){
require(
reserve0 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
} else {
require(
reserve1 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
}
oracleCreator.update(order.oracleId);
if(address(this).balance >= amountBounty){
TransferHelper.safeTransferETH(msg.sender, amountBounty);
}
}
function withdrawExpiredOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp > order.deadline, 'GnosisProtocolRelayer: DEADLINE_NOT_REACHED');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
if (order.tokenIn == WETH) {
IWETH(WETH).withdraw(order.tokenInAmount);
TransferHelper.safeTransferETH(owner, order.tokenInAmount);
} else {
TransferHelper.safeTransfer(order.tokenIn, owner, order.tokenInAmount);
}
order.executed = true;
emit WithdrawnExpiredOrder(orderIndex);
}
// Releases tokens from Gnosis Protocol
function withdrawToken(address token) public {
IEpochTokenLocker(epochTokenLocker).withdraw(address(this), token);
if (token == WETH) {
uint balance = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(balance);
}
}
// Internal function to return the pair address on a given factory
function _pair(address tokenA, address tokenB, address factory) internal view returns (address pair) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
pair = IDXswapFactory(factory).getPair(tokenA, tokenB);
}
// Returns an OrderIndex that is used to reference liquidity orders
function _OrderIndex() internal returns(uint256 orderIndex){
orderIndex = orderCount;
orderCount++;
}
// Allows the owner to withdraw any ERC20 from the relayer
function ERC20Withdraw(address token, uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransfer(token, owner, amount);
}
// Allows the owner to withdraw any ETH amount from the relayer
function ETHWithdraw(uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransferETH(owner, amount);
}
// Returns the data of one specific order
function GetOrderDetails(uint256 orderIndex) external view returns (Order memory) {
return orders[orderIndex];
}
receive() external payable {}
} | updateOracle | function updateOracle(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(!oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_ENDED');
uint256 amountBounty = GAS_ORACLE_UPDATE.mul(tx.gasprice).add(BOUNTY);
(uint reserve0, uint reserve1,) = IDXswapPair(order.oraclePair).getReserves();
address token0 = IDXswapPair(order.oraclePair).token0();
address tokenIn = order.tokenIn == address(0) ? WETH : order.tokenIn;
// Makes sure the reserve of TokenIn is higher then minReserve
if(tokenIn == token0){
require(
reserve0 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
} else {
require(
reserve1 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
}
oracleCreator.update(order.oracleId);
if(address(this).balance >= amountBounty){
TransferHelper.safeTransferETH(msg.sender, amountBounty);
}
}
| // Updates a price oracle and sends a bounty to msg.sender | LineComment | v0.6.6+commit.6c089d02 | None | ipfs://3da53e99b923809ac33371e120e9afc1422099da2e25198361b809b5b41874a6 | {
"func_code_index": [
7142,
8464
]
} | 55,915 |
||
GnosisProtocolRelayer | contracts/GnosisProtocolRelayer.sol | 0x30aad48f5ea5e8b2277612eb2a375fc173bb049e | Solidity | GnosisProtocolRelayer | contract GnosisProtocolRelayer {
using SafeMath for uint256;
event NewOrder(
uint256 indexed _orderIndex
);
event PlacedTrade(
uint256 indexed _orderIndex,
uint256 _gpOrderID
);
event WithdrawnExpiredOrder(
uint256 indexed _orderIndex
);
struct Order {
address tokenIn;
address tokenOut;
uint128 tokenInAmount;
uint128 tokenOutAmount;
uint256 priceTolerance;
uint256 minReserve;
address oraclePair;
uint256 deadline;
uint256 oracleId;
uint256 gpOrderId;
address factory;
bool executed;
}
uint256 public immutable GAS_ORACLE_UPDATE = 168364;
uint256 public immutable PARTS_PER_MILLION = 1000000;
uint256 public immutable BOUNTY = 0.01 ether; // To be decided
uint256 public immutable ORACLE_WINDOW_TIME = 120; // 2 Minutes
uint32 public immutable BATCH_TIME;
uint32 public immutable UINT32_MAX_VALUE = 2**32 - 1;
uint128 public immutable UINT128_MAX_VALUE = 2**128 - 1;
address public immutable batchExchange;
address public immutable epochTokenLocker;
address payable public immutable owner;
address public immutable WETH;
OracleCreator public oracleCreator;
uint256 public orderCount;
mapping(uint256 => Order) public orders;
mapping(address => bool) public exchangeFactoryWhitelist;
constructor(
address payable _owner,
address _batchExchange,
address _epochTokenLocker,
address[] memory _factoryWhitelist,
address _WETH,
OracleCreator _oracleCreater
) public {
require(_factoryWhitelist.length > 0, 'GnosisProtocolRelayer: MISSING_FACTORY_WHITELIST');
batchExchange = _batchExchange;
epochTokenLocker = _epochTokenLocker;
oracleCreator = _oracleCreater;
owner = _owner;
WETH = _WETH;
BATCH_TIME = IEpochTokenLocker(_epochTokenLocker).BATCH_TIME();
for (uint i=0; i < _factoryWhitelist.length; i++) {
exchangeFactoryWhitelist[_factoryWhitelist[i]] = true;
}
}
function orderTrade(
address tokenIn,
address tokenOut,
uint128 tokenInAmount,
uint128 tokenOutAmount,
uint256 priceTolerance,
uint256 minReserve,
uint256 deadline,
address factory
) external payable returns (uint256 orderIndex) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(tokenIn != tokenOut, 'GnosisProtocolRelayer: INVALID_PAIR');
require(tokenInAmount > 0 && tokenOutAmount > 0, 'GnosisProtocolRelayer: INVALID_TOKEN_AMOUNT');
require(priceTolerance <= PARTS_PER_MILLION, 'GnosisProtocolRelayer: INVALID_TOLERANCE');
require(deadline <= UINT32_MAX_VALUE, 'GnosisProtocolRelayer: INVALID_DEADLINE');
require(block.timestamp <= deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
if (tokenIn == address(0)) {
require(msg.value >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_ETH');
tokenIn = WETH;
IWETH(WETH).deposit{value: tokenInAmount}();
} else if (tokenOut == address(0)) {
tokenOut = WETH;
}
require(IERC20(tokenIn).balanceOf(address(this)) >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_TOKEN_IN');
address pair = _pair(tokenIn, tokenOut, factory);
require(pair != address(0), 'GnosisProtocolRelayer: UNKOWN_PAIR');
orderIndex = _OrderIndex();
orders[orderIndex] = Order({
tokenIn: tokenIn,
tokenOut: tokenOut,
tokenInAmount: tokenInAmount,
tokenOutAmount: tokenOutAmount,
priceTolerance: priceTolerance,
minReserve: minReserve,
oraclePair: pair,
deadline: deadline,
oracleId: 0,
gpOrderId: 0,
factory: factory,
executed: false
});
/* Create an oracle to calculate average price */
orders[orderIndex].oracleId = oracleCreator.createOracle(ORACLE_WINDOW_TIME, pair);
emit NewOrder(orderIndex);
}
function placeTrade(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
require(oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_RUNNING');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
order.executed = true;
/* Approve token on Gnosis Protocol */
TransferHelper.safeApprove(order.tokenIn, epochTokenLocker, order.tokenInAmount);
/* Deposit token in Gnosis Protocol */
IEpochTokenLocker(epochTokenLocker).deposit(order.tokenIn, order.tokenInAmount);
/* Lookup TokenIds in Gnosis Protocol */
uint16 sellToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenIn);
uint16 buyToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenOut);
uint256 expectedAmount = oracleCreator.consult(
order.oracleId,
order.tokenIn == address(0) ? WETH : order.tokenIn,
order.tokenInAmount
);
uint256 expectedAmountMin = expectedAmount.sub(expectedAmount.mul(order.priceTolerance) / PARTS_PER_MILLION);
uint256 expectedTokenOutAmount = order.tokenOutAmount;
require(
expectedAmountMin >= expectedTokenOutAmount.sub(expectedTokenOutAmount.mul(order.priceTolerance) / PARTS_PER_MILLION),
'GnosisProtocolRelayer: INVALID_PRICE_RANGE'
);
require(expectedAmountMin <= UINT128_MAX_VALUE,'GnosisProtocolRelayer: AMOUNT_OUT_OF_RANGE');
/* Calculate batch Deadline (5 Minutes window) */
uint32 validUntil = uint32(order.deadline/BATCH_TIME);
uint256 gpOrderId = IBatchExchange(batchExchange).placeOrder(buyToken, sellToken, validUntil, uint128(expectedAmountMin), order.tokenInAmount);
order.gpOrderId = gpOrderId;
emit PlacedTrade(orderIndex, gpOrderId);
}
function cancelOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(order.executed, 'GnosisProtocolRelayer: ORDER_NOT_EXECUTED');
uint16[] memory orderArray = new uint16[](1);
orderArray[0] = uint16(order.gpOrderId);
IBatchExchange(batchExchange).cancelOrders(orderArray);
}
// Updates a price oracle and sends a bounty to msg.sender
function updateOracle(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(!oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_ENDED');
uint256 amountBounty = GAS_ORACLE_UPDATE.mul(tx.gasprice).add(BOUNTY);
(uint reserve0, uint reserve1,) = IDXswapPair(order.oraclePair).getReserves();
address token0 = IDXswapPair(order.oraclePair).token0();
address tokenIn = order.tokenIn == address(0) ? WETH : order.tokenIn;
// Makes sure the reserve of TokenIn is higher then minReserve
if(tokenIn == token0){
require(
reserve0 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
} else {
require(
reserve1 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
}
oracleCreator.update(order.oracleId);
if(address(this).balance >= amountBounty){
TransferHelper.safeTransferETH(msg.sender, amountBounty);
}
}
function withdrawExpiredOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp > order.deadline, 'GnosisProtocolRelayer: DEADLINE_NOT_REACHED');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
if (order.tokenIn == WETH) {
IWETH(WETH).withdraw(order.tokenInAmount);
TransferHelper.safeTransferETH(owner, order.tokenInAmount);
} else {
TransferHelper.safeTransfer(order.tokenIn, owner, order.tokenInAmount);
}
order.executed = true;
emit WithdrawnExpiredOrder(orderIndex);
}
// Releases tokens from Gnosis Protocol
function withdrawToken(address token) public {
IEpochTokenLocker(epochTokenLocker).withdraw(address(this), token);
if (token == WETH) {
uint balance = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(balance);
}
}
// Internal function to return the pair address on a given factory
function _pair(address tokenA, address tokenB, address factory) internal view returns (address pair) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
pair = IDXswapFactory(factory).getPair(tokenA, tokenB);
}
// Returns an OrderIndex that is used to reference liquidity orders
function _OrderIndex() internal returns(uint256 orderIndex){
orderIndex = orderCount;
orderCount++;
}
// Allows the owner to withdraw any ERC20 from the relayer
function ERC20Withdraw(address token, uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransfer(token, owner, amount);
}
// Allows the owner to withdraw any ETH amount from the relayer
function ETHWithdraw(uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransferETH(owner, amount);
}
// Returns the data of one specific order
function GetOrderDetails(uint256 orderIndex) external view returns (Order memory) {
return orders[orderIndex];
}
receive() external payable {}
} | withdrawToken | function withdrawToken(address token) public {
IEpochTokenLocker(epochTokenLocker).withdraw(address(this), token);
if (token == WETH) {
uint balance = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(balance);
}
}
| // Releases tokens from Gnosis Protocol | LineComment | v0.6.6+commit.6c089d02 | None | ipfs://3da53e99b923809ac33371e120e9afc1422099da2e25198361b809b5b41874a6 | {
"func_code_index": [
9262,
9538
]
} | 55,916 |
||
GnosisProtocolRelayer | contracts/GnosisProtocolRelayer.sol | 0x30aad48f5ea5e8b2277612eb2a375fc173bb049e | Solidity | GnosisProtocolRelayer | contract GnosisProtocolRelayer {
using SafeMath for uint256;
event NewOrder(
uint256 indexed _orderIndex
);
event PlacedTrade(
uint256 indexed _orderIndex,
uint256 _gpOrderID
);
event WithdrawnExpiredOrder(
uint256 indexed _orderIndex
);
struct Order {
address tokenIn;
address tokenOut;
uint128 tokenInAmount;
uint128 tokenOutAmount;
uint256 priceTolerance;
uint256 minReserve;
address oraclePair;
uint256 deadline;
uint256 oracleId;
uint256 gpOrderId;
address factory;
bool executed;
}
uint256 public immutable GAS_ORACLE_UPDATE = 168364;
uint256 public immutable PARTS_PER_MILLION = 1000000;
uint256 public immutable BOUNTY = 0.01 ether; // To be decided
uint256 public immutable ORACLE_WINDOW_TIME = 120; // 2 Minutes
uint32 public immutable BATCH_TIME;
uint32 public immutable UINT32_MAX_VALUE = 2**32 - 1;
uint128 public immutable UINT128_MAX_VALUE = 2**128 - 1;
address public immutable batchExchange;
address public immutable epochTokenLocker;
address payable public immutable owner;
address public immutable WETH;
OracleCreator public oracleCreator;
uint256 public orderCount;
mapping(uint256 => Order) public orders;
mapping(address => bool) public exchangeFactoryWhitelist;
constructor(
address payable _owner,
address _batchExchange,
address _epochTokenLocker,
address[] memory _factoryWhitelist,
address _WETH,
OracleCreator _oracleCreater
) public {
require(_factoryWhitelist.length > 0, 'GnosisProtocolRelayer: MISSING_FACTORY_WHITELIST');
batchExchange = _batchExchange;
epochTokenLocker = _epochTokenLocker;
oracleCreator = _oracleCreater;
owner = _owner;
WETH = _WETH;
BATCH_TIME = IEpochTokenLocker(_epochTokenLocker).BATCH_TIME();
for (uint i=0; i < _factoryWhitelist.length; i++) {
exchangeFactoryWhitelist[_factoryWhitelist[i]] = true;
}
}
function orderTrade(
address tokenIn,
address tokenOut,
uint128 tokenInAmount,
uint128 tokenOutAmount,
uint256 priceTolerance,
uint256 minReserve,
uint256 deadline,
address factory
) external payable returns (uint256 orderIndex) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(tokenIn != tokenOut, 'GnosisProtocolRelayer: INVALID_PAIR');
require(tokenInAmount > 0 && tokenOutAmount > 0, 'GnosisProtocolRelayer: INVALID_TOKEN_AMOUNT');
require(priceTolerance <= PARTS_PER_MILLION, 'GnosisProtocolRelayer: INVALID_TOLERANCE');
require(deadline <= UINT32_MAX_VALUE, 'GnosisProtocolRelayer: INVALID_DEADLINE');
require(block.timestamp <= deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
if (tokenIn == address(0)) {
require(msg.value >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_ETH');
tokenIn = WETH;
IWETH(WETH).deposit{value: tokenInAmount}();
} else if (tokenOut == address(0)) {
tokenOut = WETH;
}
require(IERC20(tokenIn).balanceOf(address(this)) >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_TOKEN_IN');
address pair = _pair(tokenIn, tokenOut, factory);
require(pair != address(0), 'GnosisProtocolRelayer: UNKOWN_PAIR');
orderIndex = _OrderIndex();
orders[orderIndex] = Order({
tokenIn: tokenIn,
tokenOut: tokenOut,
tokenInAmount: tokenInAmount,
tokenOutAmount: tokenOutAmount,
priceTolerance: priceTolerance,
minReserve: minReserve,
oraclePair: pair,
deadline: deadline,
oracleId: 0,
gpOrderId: 0,
factory: factory,
executed: false
});
/* Create an oracle to calculate average price */
orders[orderIndex].oracleId = oracleCreator.createOracle(ORACLE_WINDOW_TIME, pair);
emit NewOrder(orderIndex);
}
function placeTrade(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
require(oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_RUNNING');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
order.executed = true;
/* Approve token on Gnosis Protocol */
TransferHelper.safeApprove(order.tokenIn, epochTokenLocker, order.tokenInAmount);
/* Deposit token in Gnosis Protocol */
IEpochTokenLocker(epochTokenLocker).deposit(order.tokenIn, order.tokenInAmount);
/* Lookup TokenIds in Gnosis Protocol */
uint16 sellToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenIn);
uint16 buyToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenOut);
uint256 expectedAmount = oracleCreator.consult(
order.oracleId,
order.tokenIn == address(0) ? WETH : order.tokenIn,
order.tokenInAmount
);
uint256 expectedAmountMin = expectedAmount.sub(expectedAmount.mul(order.priceTolerance) / PARTS_PER_MILLION);
uint256 expectedTokenOutAmount = order.tokenOutAmount;
require(
expectedAmountMin >= expectedTokenOutAmount.sub(expectedTokenOutAmount.mul(order.priceTolerance) / PARTS_PER_MILLION),
'GnosisProtocolRelayer: INVALID_PRICE_RANGE'
);
require(expectedAmountMin <= UINT128_MAX_VALUE,'GnosisProtocolRelayer: AMOUNT_OUT_OF_RANGE');
/* Calculate batch Deadline (5 Minutes window) */
uint32 validUntil = uint32(order.deadline/BATCH_TIME);
uint256 gpOrderId = IBatchExchange(batchExchange).placeOrder(buyToken, sellToken, validUntil, uint128(expectedAmountMin), order.tokenInAmount);
order.gpOrderId = gpOrderId;
emit PlacedTrade(orderIndex, gpOrderId);
}
function cancelOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(order.executed, 'GnosisProtocolRelayer: ORDER_NOT_EXECUTED');
uint16[] memory orderArray = new uint16[](1);
orderArray[0] = uint16(order.gpOrderId);
IBatchExchange(batchExchange).cancelOrders(orderArray);
}
// Updates a price oracle and sends a bounty to msg.sender
function updateOracle(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(!oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_ENDED');
uint256 amountBounty = GAS_ORACLE_UPDATE.mul(tx.gasprice).add(BOUNTY);
(uint reserve0, uint reserve1,) = IDXswapPair(order.oraclePair).getReserves();
address token0 = IDXswapPair(order.oraclePair).token0();
address tokenIn = order.tokenIn == address(0) ? WETH : order.tokenIn;
// Makes sure the reserve of TokenIn is higher then minReserve
if(tokenIn == token0){
require(
reserve0 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
} else {
require(
reserve1 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
}
oracleCreator.update(order.oracleId);
if(address(this).balance >= amountBounty){
TransferHelper.safeTransferETH(msg.sender, amountBounty);
}
}
function withdrawExpiredOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp > order.deadline, 'GnosisProtocolRelayer: DEADLINE_NOT_REACHED');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
if (order.tokenIn == WETH) {
IWETH(WETH).withdraw(order.tokenInAmount);
TransferHelper.safeTransferETH(owner, order.tokenInAmount);
} else {
TransferHelper.safeTransfer(order.tokenIn, owner, order.tokenInAmount);
}
order.executed = true;
emit WithdrawnExpiredOrder(orderIndex);
}
// Releases tokens from Gnosis Protocol
function withdrawToken(address token) public {
IEpochTokenLocker(epochTokenLocker).withdraw(address(this), token);
if (token == WETH) {
uint balance = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(balance);
}
}
// Internal function to return the pair address on a given factory
function _pair(address tokenA, address tokenB, address factory) internal view returns (address pair) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
pair = IDXswapFactory(factory).getPair(tokenA, tokenB);
}
// Returns an OrderIndex that is used to reference liquidity orders
function _OrderIndex() internal returns(uint256 orderIndex){
orderIndex = orderCount;
orderCount++;
}
// Allows the owner to withdraw any ERC20 from the relayer
function ERC20Withdraw(address token, uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransfer(token, owner, amount);
}
// Allows the owner to withdraw any ETH amount from the relayer
function ETHWithdraw(uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransferETH(owner, amount);
}
// Returns the data of one specific order
function GetOrderDetails(uint256 orderIndex) external view returns (Order memory) {
return orders[orderIndex];
}
receive() external payable {}
} | _pair | function _pair(address tokenA, address tokenB, address factory) internal view returns (address pair) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
pair = IDXswapFactory(factory).getPair(tokenA, tokenB);
}
| // Internal function to return the pair address on a given factory | LineComment | v0.6.6+commit.6c089d02 | None | ipfs://3da53e99b923809ac33371e120e9afc1422099da2e25198361b809b5b41874a6 | {
"func_code_index": [
9613,
9883
]
} | 55,917 |
||
GnosisProtocolRelayer | contracts/GnosisProtocolRelayer.sol | 0x30aad48f5ea5e8b2277612eb2a375fc173bb049e | Solidity | GnosisProtocolRelayer | contract GnosisProtocolRelayer {
using SafeMath for uint256;
event NewOrder(
uint256 indexed _orderIndex
);
event PlacedTrade(
uint256 indexed _orderIndex,
uint256 _gpOrderID
);
event WithdrawnExpiredOrder(
uint256 indexed _orderIndex
);
struct Order {
address tokenIn;
address tokenOut;
uint128 tokenInAmount;
uint128 tokenOutAmount;
uint256 priceTolerance;
uint256 minReserve;
address oraclePair;
uint256 deadline;
uint256 oracleId;
uint256 gpOrderId;
address factory;
bool executed;
}
uint256 public immutable GAS_ORACLE_UPDATE = 168364;
uint256 public immutable PARTS_PER_MILLION = 1000000;
uint256 public immutable BOUNTY = 0.01 ether; // To be decided
uint256 public immutable ORACLE_WINDOW_TIME = 120; // 2 Minutes
uint32 public immutable BATCH_TIME;
uint32 public immutable UINT32_MAX_VALUE = 2**32 - 1;
uint128 public immutable UINT128_MAX_VALUE = 2**128 - 1;
address public immutable batchExchange;
address public immutable epochTokenLocker;
address payable public immutable owner;
address public immutable WETH;
OracleCreator public oracleCreator;
uint256 public orderCount;
mapping(uint256 => Order) public orders;
mapping(address => bool) public exchangeFactoryWhitelist;
constructor(
address payable _owner,
address _batchExchange,
address _epochTokenLocker,
address[] memory _factoryWhitelist,
address _WETH,
OracleCreator _oracleCreater
) public {
require(_factoryWhitelist.length > 0, 'GnosisProtocolRelayer: MISSING_FACTORY_WHITELIST');
batchExchange = _batchExchange;
epochTokenLocker = _epochTokenLocker;
oracleCreator = _oracleCreater;
owner = _owner;
WETH = _WETH;
BATCH_TIME = IEpochTokenLocker(_epochTokenLocker).BATCH_TIME();
for (uint i=0; i < _factoryWhitelist.length; i++) {
exchangeFactoryWhitelist[_factoryWhitelist[i]] = true;
}
}
function orderTrade(
address tokenIn,
address tokenOut,
uint128 tokenInAmount,
uint128 tokenOutAmount,
uint256 priceTolerance,
uint256 minReserve,
uint256 deadline,
address factory
) external payable returns (uint256 orderIndex) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(tokenIn != tokenOut, 'GnosisProtocolRelayer: INVALID_PAIR');
require(tokenInAmount > 0 && tokenOutAmount > 0, 'GnosisProtocolRelayer: INVALID_TOKEN_AMOUNT');
require(priceTolerance <= PARTS_PER_MILLION, 'GnosisProtocolRelayer: INVALID_TOLERANCE');
require(deadline <= UINT32_MAX_VALUE, 'GnosisProtocolRelayer: INVALID_DEADLINE');
require(block.timestamp <= deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
if (tokenIn == address(0)) {
require(msg.value >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_ETH');
tokenIn = WETH;
IWETH(WETH).deposit{value: tokenInAmount}();
} else if (tokenOut == address(0)) {
tokenOut = WETH;
}
require(IERC20(tokenIn).balanceOf(address(this)) >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_TOKEN_IN');
address pair = _pair(tokenIn, tokenOut, factory);
require(pair != address(0), 'GnosisProtocolRelayer: UNKOWN_PAIR');
orderIndex = _OrderIndex();
orders[orderIndex] = Order({
tokenIn: tokenIn,
tokenOut: tokenOut,
tokenInAmount: tokenInAmount,
tokenOutAmount: tokenOutAmount,
priceTolerance: priceTolerance,
minReserve: minReserve,
oraclePair: pair,
deadline: deadline,
oracleId: 0,
gpOrderId: 0,
factory: factory,
executed: false
});
/* Create an oracle to calculate average price */
orders[orderIndex].oracleId = oracleCreator.createOracle(ORACLE_WINDOW_TIME, pair);
emit NewOrder(orderIndex);
}
function placeTrade(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
require(oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_RUNNING');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
order.executed = true;
/* Approve token on Gnosis Protocol */
TransferHelper.safeApprove(order.tokenIn, epochTokenLocker, order.tokenInAmount);
/* Deposit token in Gnosis Protocol */
IEpochTokenLocker(epochTokenLocker).deposit(order.tokenIn, order.tokenInAmount);
/* Lookup TokenIds in Gnosis Protocol */
uint16 sellToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenIn);
uint16 buyToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenOut);
uint256 expectedAmount = oracleCreator.consult(
order.oracleId,
order.tokenIn == address(0) ? WETH : order.tokenIn,
order.tokenInAmount
);
uint256 expectedAmountMin = expectedAmount.sub(expectedAmount.mul(order.priceTolerance) / PARTS_PER_MILLION);
uint256 expectedTokenOutAmount = order.tokenOutAmount;
require(
expectedAmountMin >= expectedTokenOutAmount.sub(expectedTokenOutAmount.mul(order.priceTolerance) / PARTS_PER_MILLION),
'GnosisProtocolRelayer: INVALID_PRICE_RANGE'
);
require(expectedAmountMin <= UINT128_MAX_VALUE,'GnosisProtocolRelayer: AMOUNT_OUT_OF_RANGE');
/* Calculate batch Deadline (5 Minutes window) */
uint32 validUntil = uint32(order.deadline/BATCH_TIME);
uint256 gpOrderId = IBatchExchange(batchExchange).placeOrder(buyToken, sellToken, validUntil, uint128(expectedAmountMin), order.tokenInAmount);
order.gpOrderId = gpOrderId;
emit PlacedTrade(orderIndex, gpOrderId);
}
function cancelOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(order.executed, 'GnosisProtocolRelayer: ORDER_NOT_EXECUTED');
uint16[] memory orderArray = new uint16[](1);
orderArray[0] = uint16(order.gpOrderId);
IBatchExchange(batchExchange).cancelOrders(orderArray);
}
// Updates a price oracle and sends a bounty to msg.sender
function updateOracle(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(!oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_ENDED');
uint256 amountBounty = GAS_ORACLE_UPDATE.mul(tx.gasprice).add(BOUNTY);
(uint reserve0, uint reserve1,) = IDXswapPair(order.oraclePair).getReserves();
address token0 = IDXswapPair(order.oraclePair).token0();
address tokenIn = order.tokenIn == address(0) ? WETH : order.tokenIn;
// Makes sure the reserve of TokenIn is higher then minReserve
if(tokenIn == token0){
require(
reserve0 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
} else {
require(
reserve1 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
}
oracleCreator.update(order.oracleId);
if(address(this).balance >= amountBounty){
TransferHelper.safeTransferETH(msg.sender, amountBounty);
}
}
function withdrawExpiredOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp > order.deadline, 'GnosisProtocolRelayer: DEADLINE_NOT_REACHED');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
if (order.tokenIn == WETH) {
IWETH(WETH).withdraw(order.tokenInAmount);
TransferHelper.safeTransferETH(owner, order.tokenInAmount);
} else {
TransferHelper.safeTransfer(order.tokenIn, owner, order.tokenInAmount);
}
order.executed = true;
emit WithdrawnExpiredOrder(orderIndex);
}
// Releases tokens from Gnosis Protocol
function withdrawToken(address token) public {
IEpochTokenLocker(epochTokenLocker).withdraw(address(this), token);
if (token == WETH) {
uint balance = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(balance);
}
}
// Internal function to return the pair address on a given factory
function _pair(address tokenA, address tokenB, address factory) internal view returns (address pair) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
pair = IDXswapFactory(factory).getPair(tokenA, tokenB);
}
// Returns an OrderIndex that is used to reference liquidity orders
function _OrderIndex() internal returns(uint256 orderIndex){
orderIndex = orderCount;
orderCount++;
}
// Allows the owner to withdraw any ERC20 from the relayer
function ERC20Withdraw(address token, uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransfer(token, owner, amount);
}
// Allows the owner to withdraw any ETH amount from the relayer
function ETHWithdraw(uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransferETH(owner, amount);
}
// Returns the data of one specific order
function GetOrderDetails(uint256 orderIndex) external view returns (Order memory) {
return orders[orderIndex];
}
receive() external payable {}
} | _OrderIndex | function _OrderIndex() internal returns(uint256 orderIndex){
orderIndex = orderCount;
orderCount++;
}
| // Returns an OrderIndex that is used to reference liquidity orders | LineComment | v0.6.6+commit.6c089d02 | None | ipfs://3da53e99b923809ac33371e120e9afc1422099da2e25198361b809b5b41874a6 | {
"func_code_index": [
9959,
10088
]
} | 55,918 |
||
GnosisProtocolRelayer | contracts/GnosisProtocolRelayer.sol | 0x30aad48f5ea5e8b2277612eb2a375fc173bb049e | Solidity | GnosisProtocolRelayer | contract GnosisProtocolRelayer {
using SafeMath for uint256;
event NewOrder(
uint256 indexed _orderIndex
);
event PlacedTrade(
uint256 indexed _orderIndex,
uint256 _gpOrderID
);
event WithdrawnExpiredOrder(
uint256 indexed _orderIndex
);
struct Order {
address tokenIn;
address tokenOut;
uint128 tokenInAmount;
uint128 tokenOutAmount;
uint256 priceTolerance;
uint256 minReserve;
address oraclePair;
uint256 deadline;
uint256 oracleId;
uint256 gpOrderId;
address factory;
bool executed;
}
uint256 public immutable GAS_ORACLE_UPDATE = 168364;
uint256 public immutable PARTS_PER_MILLION = 1000000;
uint256 public immutable BOUNTY = 0.01 ether; // To be decided
uint256 public immutable ORACLE_WINDOW_TIME = 120; // 2 Minutes
uint32 public immutable BATCH_TIME;
uint32 public immutable UINT32_MAX_VALUE = 2**32 - 1;
uint128 public immutable UINT128_MAX_VALUE = 2**128 - 1;
address public immutable batchExchange;
address public immutable epochTokenLocker;
address payable public immutable owner;
address public immutable WETH;
OracleCreator public oracleCreator;
uint256 public orderCount;
mapping(uint256 => Order) public orders;
mapping(address => bool) public exchangeFactoryWhitelist;
constructor(
address payable _owner,
address _batchExchange,
address _epochTokenLocker,
address[] memory _factoryWhitelist,
address _WETH,
OracleCreator _oracleCreater
) public {
require(_factoryWhitelist.length > 0, 'GnosisProtocolRelayer: MISSING_FACTORY_WHITELIST');
batchExchange = _batchExchange;
epochTokenLocker = _epochTokenLocker;
oracleCreator = _oracleCreater;
owner = _owner;
WETH = _WETH;
BATCH_TIME = IEpochTokenLocker(_epochTokenLocker).BATCH_TIME();
for (uint i=0; i < _factoryWhitelist.length; i++) {
exchangeFactoryWhitelist[_factoryWhitelist[i]] = true;
}
}
function orderTrade(
address tokenIn,
address tokenOut,
uint128 tokenInAmount,
uint128 tokenOutAmount,
uint256 priceTolerance,
uint256 minReserve,
uint256 deadline,
address factory
) external payable returns (uint256 orderIndex) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(tokenIn != tokenOut, 'GnosisProtocolRelayer: INVALID_PAIR');
require(tokenInAmount > 0 && tokenOutAmount > 0, 'GnosisProtocolRelayer: INVALID_TOKEN_AMOUNT');
require(priceTolerance <= PARTS_PER_MILLION, 'GnosisProtocolRelayer: INVALID_TOLERANCE');
require(deadline <= UINT32_MAX_VALUE, 'GnosisProtocolRelayer: INVALID_DEADLINE');
require(block.timestamp <= deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
if (tokenIn == address(0)) {
require(msg.value >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_ETH');
tokenIn = WETH;
IWETH(WETH).deposit{value: tokenInAmount}();
} else if (tokenOut == address(0)) {
tokenOut = WETH;
}
require(IERC20(tokenIn).balanceOf(address(this)) >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_TOKEN_IN');
address pair = _pair(tokenIn, tokenOut, factory);
require(pair != address(0), 'GnosisProtocolRelayer: UNKOWN_PAIR');
orderIndex = _OrderIndex();
orders[orderIndex] = Order({
tokenIn: tokenIn,
tokenOut: tokenOut,
tokenInAmount: tokenInAmount,
tokenOutAmount: tokenOutAmount,
priceTolerance: priceTolerance,
minReserve: minReserve,
oraclePair: pair,
deadline: deadline,
oracleId: 0,
gpOrderId: 0,
factory: factory,
executed: false
});
/* Create an oracle to calculate average price */
orders[orderIndex].oracleId = oracleCreator.createOracle(ORACLE_WINDOW_TIME, pair);
emit NewOrder(orderIndex);
}
function placeTrade(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
require(oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_RUNNING');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
order.executed = true;
/* Approve token on Gnosis Protocol */
TransferHelper.safeApprove(order.tokenIn, epochTokenLocker, order.tokenInAmount);
/* Deposit token in Gnosis Protocol */
IEpochTokenLocker(epochTokenLocker).deposit(order.tokenIn, order.tokenInAmount);
/* Lookup TokenIds in Gnosis Protocol */
uint16 sellToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenIn);
uint16 buyToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenOut);
uint256 expectedAmount = oracleCreator.consult(
order.oracleId,
order.tokenIn == address(0) ? WETH : order.tokenIn,
order.tokenInAmount
);
uint256 expectedAmountMin = expectedAmount.sub(expectedAmount.mul(order.priceTolerance) / PARTS_PER_MILLION);
uint256 expectedTokenOutAmount = order.tokenOutAmount;
require(
expectedAmountMin >= expectedTokenOutAmount.sub(expectedTokenOutAmount.mul(order.priceTolerance) / PARTS_PER_MILLION),
'GnosisProtocolRelayer: INVALID_PRICE_RANGE'
);
require(expectedAmountMin <= UINT128_MAX_VALUE,'GnosisProtocolRelayer: AMOUNT_OUT_OF_RANGE');
/* Calculate batch Deadline (5 Minutes window) */
uint32 validUntil = uint32(order.deadline/BATCH_TIME);
uint256 gpOrderId = IBatchExchange(batchExchange).placeOrder(buyToken, sellToken, validUntil, uint128(expectedAmountMin), order.tokenInAmount);
order.gpOrderId = gpOrderId;
emit PlacedTrade(orderIndex, gpOrderId);
}
function cancelOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(order.executed, 'GnosisProtocolRelayer: ORDER_NOT_EXECUTED');
uint16[] memory orderArray = new uint16[](1);
orderArray[0] = uint16(order.gpOrderId);
IBatchExchange(batchExchange).cancelOrders(orderArray);
}
// Updates a price oracle and sends a bounty to msg.sender
function updateOracle(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(!oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_ENDED');
uint256 amountBounty = GAS_ORACLE_UPDATE.mul(tx.gasprice).add(BOUNTY);
(uint reserve0, uint reserve1,) = IDXswapPair(order.oraclePair).getReserves();
address token0 = IDXswapPair(order.oraclePair).token0();
address tokenIn = order.tokenIn == address(0) ? WETH : order.tokenIn;
// Makes sure the reserve of TokenIn is higher then minReserve
if(tokenIn == token0){
require(
reserve0 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
} else {
require(
reserve1 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
}
oracleCreator.update(order.oracleId);
if(address(this).balance >= amountBounty){
TransferHelper.safeTransferETH(msg.sender, amountBounty);
}
}
function withdrawExpiredOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp > order.deadline, 'GnosisProtocolRelayer: DEADLINE_NOT_REACHED');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
if (order.tokenIn == WETH) {
IWETH(WETH).withdraw(order.tokenInAmount);
TransferHelper.safeTransferETH(owner, order.tokenInAmount);
} else {
TransferHelper.safeTransfer(order.tokenIn, owner, order.tokenInAmount);
}
order.executed = true;
emit WithdrawnExpiredOrder(orderIndex);
}
// Releases tokens from Gnosis Protocol
function withdrawToken(address token) public {
IEpochTokenLocker(epochTokenLocker).withdraw(address(this), token);
if (token == WETH) {
uint balance = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(balance);
}
}
// Internal function to return the pair address on a given factory
function _pair(address tokenA, address tokenB, address factory) internal view returns (address pair) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
pair = IDXswapFactory(factory).getPair(tokenA, tokenB);
}
// Returns an OrderIndex that is used to reference liquidity orders
function _OrderIndex() internal returns(uint256 orderIndex){
orderIndex = orderCount;
orderCount++;
}
// Allows the owner to withdraw any ERC20 from the relayer
function ERC20Withdraw(address token, uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransfer(token, owner, amount);
}
// Allows the owner to withdraw any ETH amount from the relayer
function ETHWithdraw(uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransferETH(owner, amount);
}
// Returns the data of one specific order
function GetOrderDetails(uint256 orderIndex) external view returns (Order memory) {
return orders[orderIndex];
}
receive() external payable {}
} | ERC20Withdraw | function ERC20Withdraw(address token, uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransfer(token, owner, amount);
}
| // Allows the owner to withdraw any ERC20 from the relayer | LineComment | v0.6.6+commit.6c089d02 | None | ipfs://3da53e99b923809ac33371e120e9afc1422099da2e25198361b809b5b41874a6 | {
"func_code_index": [
10159,
10377
]
} | 55,919 |
||
GnosisProtocolRelayer | contracts/GnosisProtocolRelayer.sol | 0x30aad48f5ea5e8b2277612eb2a375fc173bb049e | Solidity | GnosisProtocolRelayer | contract GnosisProtocolRelayer {
using SafeMath for uint256;
event NewOrder(
uint256 indexed _orderIndex
);
event PlacedTrade(
uint256 indexed _orderIndex,
uint256 _gpOrderID
);
event WithdrawnExpiredOrder(
uint256 indexed _orderIndex
);
struct Order {
address tokenIn;
address tokenOut;
uint128 tokenInAmount;
uint128 tokenOutAmount;
uint256 priceTolerance;
uint256 minReserve;
address oraclePair;
uint256 deadline;
uint256 oracleId;
uint256 gpOrderId;
address factory;
bool executed;
}
uint256 public immutable GAS_ORACLE_UPDATE = 168364;
uint256 public immutable PARTS_PER_MILLION = 1000000;
uint256 public immutable BOUNTY = 0.01 ether; // To be decided
uint256 public immutable ORACLE_WINDOW_TIME = 120; // 2 Minutes
uint32 public immutable BATCH_TIME;
uint32 public immutable UINT32_MAX_VALUE = 2**32 - 1;
uint128 public immutable UINT128_MAX_VALUE = 2**128 - 1;
address public immutable batchExchange;
address public immutable epochTokenLocker;
address payable public immutable owner;
address public immutable WETH;
OracleCreator public oracleCreator;
uint256 public orderCount;
mapping(uint256 => Order) public orders;
mapping(address => bool) public exchangeFactoryWhitelist;
constructor(
address payable _owner,
address _batchExchange,
address _epochTokenLocker,
address[] memory _factoryWhitelist,
address _WETH,
OracleCreator _oracleCreater
) public {
require(_factoryWhitelist.length > 0, 'GnosisProtocolRelayer: MISSING_FACTORY_WHITELIST');
batchExchange = _batchExchange;
epochTokenLocker = _epochTokenLocker;
oracleCreator = _oracleCreater;
owner = _owner;
WETH = _WETH;
BATCH_TIME = IEpochTokenLocker(_epochTokenLocker).BATCH_TIME();
for (uint i=0; i < _factoryWhitelist.length; i++) {
exchangeFactoryWhitelist[_factoryWhitelist[i]] = true;
}
}
function orderTrade(
address tokenIn,
address tokenOut,
uint128 tokenInAmount,
uint128 tokenOutAmount,
uint256 priceTolerance,
uint256 minReserve,
uint256 deadline,
address factory
) external payable returns (uint256 orderIndex) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(tokenIn != tokenOut, 'GnosisProtocolRelayer: INVALID_PAIR');
require(tokenInAmount > 0 && tokenOutAmount > 0, 'GnosisProtocolRelayer: INVALID_TOKEN_AMOUNT');
require(priceTolerance <= PARTS_PER_MILLION, 'GnosisProtocolRelayer: INVALID_TOLERANCE');
require(deadline <= UINT32_MAX_VALUE, 'GnosisProtocolRelayer: INVALID_DEADLINE');
require(block.timestamp <= deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
if (tokenIn == address(0)) {
require(msg.value >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_ETH');
tokenIn = WETH;
IWETH(WETH).deposit{value: tokenInAmount}();
} else if (tokenOut == address(0)) {
tokenOut = WETH;
}
require(IERC20(tokenIn).balanceOf(address(this)) >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_TOKEN_IN');
address pair = _pair(tokenIn, tokenOut, factory);
require(pair != address(0), 'GnosisProtocolRelayer: UNKOWN_PAIR');
orderIndex = _OrderIndex();
orders[orderIndex] = Order({
tokenIn: tokenIn,
tokenOut: tokenOut,
tokenInAmount: tokenInAmount,
tokenOutAmount: tokenOutAmount,
priceTolerance: priceTolerance,
minReserve: minReserve,
oraclePair: pair,
deadline: deadline,
oracleId: 0,
gpOrderId: 0,
factory: factory,
executed: false
});
/* Create an oracle to calculate average price */
orders[orderIndex].oracleId = oracleCreator.createOracle(ORACLE_WINDOW_TIME, pair);
emit NewOrder(orderIndex);
}
function placeTrade(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
require(oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_RUNNING');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
order.executed = true;
/* Approve token on Gnosis Protocol */
TransferHelper.safeApprove(order.tokenIn, epochTokenLocker, order.tokenInAmount);
/* Deposit token in Gnosis Protocol */
IEpochTokenLocker(epochTokenLocker).deposit(order.tokenIn, order.tokenInAmount);
/* Lookup TokenIds in Gnosis Protocol */
uint16 sellToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenIn);
uint16 buyToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenOut);
uint256 expectedAmount = oracleCreator.consult(
order.oracleId,
order.tokenIn == address(0) ? WETH : order.tokenIn,
order.tokenInAmount
);
uint256 expectedAmountMin = expectedAmount.sub(expectedAmount.mul(order.priceTolerance) / PARTS_PER_MILLION);
uint256 expectedTokenOutAmount = order.tokenOutAmount;
require(
expectedAmountMin >= expectedTokenOutAmount.sub(expectedTokenOutAmount.mul(order.priceTolerance) / PARTS_PER_MILLION),
'GnosisProtocolRelayer: INVALID_PRICE_RANGE'
);
require(expectedAmountMin <= UINT128_MAX_VALUE,'GnosisProtocolRelayer: AMOUNT_OUT_OF_RANGE');
/* Calculate batch Deadline (5 Minutes window) */
uint32 validUntil = uint32(order.deadline/BATCH_TIME);
uint256 gpOrderId = IBatchExchange(batchExchange).placeOrder(buyToken, sellToken, validUntil, uint128(expectedAmountMin), order.tokenInAmount);
order.gpOrderId = gpOrderId;
emit PlacedTrade(orderIndex, gpOrderId);
}
function cancelOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(order.executed, 'GnosisProtocolRelayer: ORDER_NOT_EXECUTED');
uint16[] memory orderArray = new uint16[](1);
orderArray[0] = uint16(order.gpOrderId);
IBatchExchange(batchExchange).cancelOrders(orderArray);
}
// Updates a price oracle and sends a bounty to msg.sender
function updateOracle(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(!oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_ENDED');
uint256 amountBounty = GAS_ORACLE_UPDATE.mul(tx.gasprice).add(BOUNTY);
(uint reserve0, uint reserve1,) = IDXswapPair(order.oraclePair).getReserves();
address token0 = IDXswapPair(order.oraclePair).token0();
address tokenIn = order.tokenIn == address(0) ? WETH : order.tokenIn;
// Makes sure the reserve of TokenIn is higher then minReserve
if(tokenIn == token0){
require(
reserve0 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
} else {
require(
reserve1 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
}
oracleCreator.update(order.oracleId);
if(address(this).balance >= amountBounty){
TransferHelper.safeTransferETH(msg.sender, amountBounty);
}
}
function withdrawExpiredOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp > order.deadline, 'GnosisProtocolRelayer: DEADLINE_NOT_REACHED');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
if (order.tokenIn == WETH) {
IWETH(WETH).withdraw(order.tokenInAmount);
TransferHelper.safeTransferETH(owner, order.tokenInAmount);
} else {
TransferHelper.safeTransfer(order.tokenIn, owner, order.tokenInAmount);
}
order.executed = true;
emit WithdrawnExpiredOrder(orderIndex);
}
// Releases tokens from Gnosis Protocol
function withdrawToken(address token) public {
IEpochTokenLocker(epochTokenLocker).withdraw(address(this), token);
if (token == WETH) {
uint balance = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(balance);
}
}
// Internal function to return the pair address on a given factory
function _pair(address tokenA, address tokenB, address factory) internal view returns (address pair) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
pair = IDXswapFactory(factory).getPair(tokenA, tokenB);
}
// Returns an OrderIndex that is used to reference liquidity orders
function _OrderIndex() internal returns(uint256 orderIndex){
orderIndex = orderCount;
orderCount++;
}
// Allows the owner to withdraw any ERC20 from the relayer
function ERC20Withdraw(address token, uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransfer(token, owner, amount);
}
// Allows the owner to withdraw any ETH amount from the relayer
function ETHWithdraw(uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransferETH(owner, amount);
}
// Returns the data of one specific order
function GetOrderDetails(uint256 orderIndex) external view returns (Order memory) {
return orders[orderIndex];
}
receive() external payable {}
} | ETHWithdraw | function ETHWithdraw(uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransferETH(owner, amount);
}
| // Allows the owner to withdraw any ETH amount from the relayer | LineComment | v0.6.6+commit.6c089d02 | None | ipfs://3da53e99b923809ac33371e120e9afc1422099da2e25198361b809b5b41874a6 | {
"func_code_index": [
10449,
10646
]
} | 55,920 |
||
GnosisProtocolRelayer | contracts/GnosisProtocolRelayer.sol | 0x30aad48f5ea5e8b2277612eb2a375fc173bb049e | Solidity | GnosisProtocolRelayer | contract GnosisProtocolRelayer {
using SafeMath for uint256;
event NewOrder(
uint256 indexed _orderIndex
);
event PlacedTrade(
uint256 indexed _orderIndex,
uint256 _gpOrderID
);
event WithdrawnExpiredOrder(
uint256 indexed _orderIndex
);
struct Order {
address tokenIn;
address tokenOut;
uint128 tokenInAmount;
uint128 tokenOutAmount;
uint256 priceTolerance;
uint256 minReserve;
address oraclePair;
uint256 deadline;
uint256 oracleId;
uint256 gpOrderId;
address factory;
bool executed;
}
uint256 public immutable GAS_ORACLE_UPDATE = 168364;
uint256 public immutable PARTS_PER_MILLION = 1000000;
uint256 public immutable BOUNTY = 0.01 ether; // To be decided
uint256 public immutable ORACLE_WINDOW_TIME = 120; // 2 Minutes
uint32 public immutable BATCH_TIME;
uint32 public immutable UINT32_MAX_VALUE = 2**32 - 1;
uint128 public immutable UINT128_MAX_VALUE = 2**128 - 1;
address public immutable batchExchange;
address public immutable epochTokenLocker;
address payable public immutable owner;
address public immutable WETH;
OracleCreator public oracleCreator;
uint256 public orderCount;
mapping(uint256 => Order) public orders;
mapping(address => bool) public exchangeFactoryWhitelist;
constructor(
address payable _owner,
address _batchExchange,
address _epochTokenLocker,
address[] memory _factoryWhitelist,
address _WETH,
OracleCreator _oracleCreater
) public {
require(_factoryWhitelist.length > 0, 'GnosisProtocolRelayer: MISSING_FACTORY_WHITELIST');
batchExchange = _batchExchange;
epochTokenLocker = _epochTokenLocker;
oracleCreator = _oracleCreater;
owner = _owner;
WETH = _WETH;
BATCH_TIME = IEpochTokenLocker(_epochTokenLocker).BATCH_TIME();
for (uint i=0; i < _factoryWhitelist.length; i++) {
exchangeFactoryWhitelist[_factoryWhitelist[i]] = true;
}
}
function orderTrade(
address tokenIn,
address tokenOut,
uint128 tokenInAmount,
uint128 tokenOutAmount,
uint256 priceTolerance,
uint256 minReserve,
uint256 deadline,
address factory
) external payable returns (uint256 orderIndex) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(tokenIn != tokenOut, 'GnosisProtocolRelayer: INVALID_PAIR');
require(tokenInAmount > 0 && tokenOutAmount > 0, 'GnosisProtocolRelayer: INVALID_TOKEN_AMOUNT');
require(priceTolerance <= PARTS_PER_MILLION, 'GnosisProtocolRelayer: INVALID_TOLERANCE');
require(deadline <= UINT32_MAX_VALUE, 'GnosisProtocolRelayer: INVALID_DEADLINE');
require(block.timestamp <= deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
if (tokenIn == address(0)) {
require(msg.value >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_ETH');
tokenIn = WETH;
IWETH(WETH).deposit{value: tokenInAmount}();
} else if (tokenOut == address(0)) {
tokenOut = WETH;
}
require(IERC20(tokenIn).balanceOf(address(this)) >= tokenInAmount, 'GnosisProtocolRelayer: INSUFFIENT_TOKEN_IN');
address pair = _pair(tokenIn, tokenOut, factory);
require(pair != address(0), 'GnosisProtocolRelayer: UNKOWN_PAIR');
orderIndex = _OrderIndex();
orders[orderIndex] = Order({
tokenIn: tokenIn,
tokenOut: tokenOut,
tokenInAmount: tokenInAmount,
tokenOutAmount: tokenOutAmount,
priceTolerance: priceTolerance,
minReserve: minReserve,
oraclePair: pair,
deadline: deadline,
oracleId: 0,
gpOrderId: 0,
factory: factory,
executed: false
});
/* Create an oracle to calculate average price */
orders[orderIndex].oracleId = oracleCreator.createOracle(ORACLE_WINDOW_TIME, pair);
emit NewOrder(orderIndex);
}
function placeTrade(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
require(oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_RUNNING');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
order.executed = true;
/* Approve token on Gnosis Protocol */
TransferHelper.safeApprove(order.tokenIn, epochTokenLocker, order.tokenInAmount);
/* Deposit token in Gnosis Protocol */
IEpochTokenLocker(epochTokenLocker).deposit(order.tokenIn, order.tokenInAmount);
/* Lookup TokenIds in Gnosis Protocol */
uint16 sellToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenIn);
uint16 buyToken = IBatchExchange(batchExchange).tokenAddressToIdMap(order.tokenOut);
uint256 expectedAmount = oracleCreator.consult(
order.oracleId,
order.tokenIn == address(0) ? WETH : order.tokenIn,
order.tokenInAmount
);
uint256 expectedAmountMin = expectedAmount.sub(expectedAmount.mul(order.priceTolerance) / PARTS_PER_MILLION);
uint256 expectedTokenOutAmount = order.tokenOutAmount;
require(
expectedAmountMin >= expectedTokenOutAmount.sub(expectedTokenOutAmount.mul(order.priceTolerance) / PARTS_PER_MILLION),
'GnosisProtocolRelayer: INVALID_PRICE_RANGE'
);
require(expectedAmountMin <= UINT128_MAX_VALUE,'GnosisProtocolRelayer: AMOUNT_OUT_OF_RANGE');
/* Calculate batch Deadline (5 Minutes window) */
uint32 validUntil = uint32(order.deadline/BATCH_TIME);
uint256 gpOrderId = IBatchExchange(batchExchange).placeOrder(buyToken, sellToken, validUntil, uint128(expectedAmountMin), order.tokenInAmount);
order.gpOrderId = gpOrderId;
emit PlacedTrade(orderIndex, gpOrderId);
}
function cancelOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
require(order.executed, 'GnosisProtocolRelayer: ORDER_NOT_EXECUTED');
uint16[] memory orderArray = new uint16[](1);
orderArray[0] = uint16(order.gpOrderId);
IBatchExchange(batchExchange).cancelOrders(orderArray);
}
// Updates a price oracle and sends a bounty to msg.sender
function updateOracle(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp <= order.deadline, 'GnosisProtocolRelayer: DEADLINE_REACHED');
require(!oracleCreator.isOracleFinalized(order.oracleId) , 'GnosisProtocolRelayer: OBSERVATION_ENDED');
uint256 amountBounty = GAS_ORACLE_UPDATE.mul(tx.gasprice).add(BOUNTY);
(uint reserve0, uint reserve1,) = IDXswapPair(order.oraclePair).getReserves();
address token0 = IDXswapPair(order.oraclePair).token0();
address tokenIn = order.tokenIn == address(0) ? WETH : order.tokenIn;
// Makes sure the reserve of TokenIn is higher then minReserve
if(tokenIn == token0){
require(
reserve0 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
} else {
require(
reserve1 >= order.minReserve,
'GnosisProtocolRelayer: RESERVE_TO_LOW'
);
}
oracleCreator.update(order.oracleId);
if(address(this).balance >= amountBounty){
TransferHelper.safeTransferETH(msg.sender, amountBounty);
}
}
function withdrawExpiredOrder(uint256 orderIndex) external {
Order storage order = orders[orderIndex];
require(orderIndex < orderCount, 'GnosisProtocolRelayer: INVALID_ORDER');
require(block.timestamp > order.deadline, 'GnosisProtocolRelayer: DEADLINE_NOT_REACHED');
require(!order.executed, 'GnosisProtocolRelayer: ORDER_EXECUTED');
if (order.tokenIn == WETH) {
IWETH(WETH).withdraw(order.tokenInAmount);
TransferHelper.safeTransferETH(owner, order.tokenInAmount);
} else {
TransferHelper.safeTransfer(order.tokenIn, owner, order.tokenInAmount);
}
order.executed = true;
emit WithdrawnExpiredOrder(orderIndex);
}
// Releases tokens from Gnosis Protocol
function withdrawToken(address token) public {
IEpochTokenLocker(epochTokenLocker).withdraw(address(this), token);
if (token == WETH) {
uint balance = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(balance);
}
}
// Internal function to return the pair address on a given factory
function _pair(address tokenA, address tokenB, address factory) internal view returns (address pair) {
require(exchangeFactoryWhitelist[factory], 'GnosisProtocolRelayer: INVALID_FACTORY');
pair = IDXswapFactory(factory).getPair(tokenA, tokenB);
}
// Returns an OrderIndex that is used to reference liquidity orders
function _OrderIndex() internal returns(uint256 orderIndex){
orderIndex = orderCount;
orderCount++;
}
// Allows the owner to withdraw any ERC20 from the relayer
function ERC20Withdraw(address token, uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransfer(token, owner, amount);
}
// Allows the owner to withdraw any ETH amount from the relayer
function ETHWithdraw(uint256 amount) external {
require(msg.sender == owner, 'GnosisProtocolRelayer: CALLER_NOT_OWNER');
TransferHelper.safeTransferETH(owner, amount);
}
// Returns the data of one specific order
function GetOrderDetails(uint256 orderIndex) external view returns (Order memory) {
return orders[orderIndex];
}
receive() external payable {}
} | GetOrderDetails | function GetOrderDetails(uint256 orderIndex) external view returns (Order memory) {
return orders[orderIndex];
}
| // Returns the data of one specific order | LineComment | v0.6.6+commit.6c089d02 | None | ipfs://3da53e99b923809ac33371e120e9afc1422099da2e25198361b809b5b41874a6 | {
"func_code_index": [
10696,
10825
]
} | 55,921 |
||
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC165 | interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | /**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/ | NatSpecMultiLine | supportsInterface | function supportsInterface(bytes4 interfaceId) external view returns (bool);
| /**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
374,
455
]
} | 55,922 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address owner) external view returns (uint256 balance);
| /**
* @dev Returns the number of tokens in ``owner``'s account.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
719,
798
]
} | 55,923 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | ownerOf | function ownerOf(uint256 tokenId) external view returns (address owner);
| /**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
944,
1021
]
} | 55,924 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | safeTransferFrom | function safeTransferFrom(address from, address to, uint256 tokenId) external;
| /**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
1733,
1816
]
} | 55,925 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address from, address to, uint256 tokenId) external;
| /**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
2342,
2421
]
} | 55,926 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | approve | function approve(address to, uint256 tokenId) external;
| /**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
2894,
2954
]
} | 55,927 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | getApproved | function getApproved(uint256 tokenId) external view returns (address operator);
| /**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
3108,
3192
]
} | 55,928 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | setApprovalForAll | function setApprovalForAll(address operator, bool _approved) external;
| /**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
3519,
3594
]
} | 55,929 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | isApprovedForAll | function isApprovedForAll(address owner, address operator) external view returns (bool);
| /**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
3745,
3838
]
} | 55,930 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | safeTransferFrom | function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
| /**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
4427,
4531
]
} | 55,931 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721Metadata | interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | name | function name() external view returns (string memory);
| /**
* @dev Returns the token collection name.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
108,
167
]
} | 55,932 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721Metadata | interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | symbol | function symbol() external view returns (string memory);
| /**
* @dev Returns the token collection symbol.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
238,
299
]
} | 55,933 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721Metadata | interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | tokenURI | function tokenURI(uint256 tokenId) external view returns (string memory);
| /**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
400,
478
]
} | 55,934 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721Enumerable | interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the total amount of tokens stored by the contract.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
134,
194
]
} | 55,935 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721Enumerable | interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | tokenOfOwnerByIndex | function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
| /**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
377,
481
]
} | 55,936 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721Enumerable | interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
} | /**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/ | NatSpecMultiLine | tokenByIndex | function tokenByIndex(uint256 index) external view returns (uint256);
| /**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
657,
731
]
} | 55,937 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | IERC721Receiver | interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
} | /**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/ | NatSpecMultiLine | onERC721Received | function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
| /**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
528,
655
]
} | 55,938 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | ERC165 | abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
} | /**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/ | NatSpecMultiLine | supportsInterface | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
| /**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
711,
866
]
} | 55,939 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | Solidity | ERC165 | abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
} | /**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/ | NatSpecMultiLine | _registerInterface | function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
| /**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
1268,
1474
]
} | 55,940 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | tryAdd | function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
161,
344
]
} | 55,941 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | trySub | function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
492,
651
]
} | 55,942 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | tryMul | function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
801,
1249
]
} | 55,943 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | tryDiv | function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
1400,
1560
]
} | 55,944 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | tryMod | function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
1721,
1881
]
} | 55,945 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| /**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
2123,
2307
]
} | 55,946 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
2585,
2748
]
} | 55,947 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| /**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
3002,
3227
]
} | 55,948 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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. 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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
3700,
3858
]
} | 55,949 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* 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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
4320,
4476
]
} | 55,950 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
4950,
5121
]
} | 55,951 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
5790,
5960
]
} | 55,952 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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) {
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) {
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) {
// 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) {
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) {
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) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
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) {
require(b > 0, "SafeMath: modulo by zero");
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) {
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.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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) {
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) {
require(b > 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
6618,
6788
]
} | 55,953 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | 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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
606,
1033
]
} | 55,954 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | sendValue | function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// 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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
1963,
2365
]
} | 55,955 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| /**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
3121,
3299
]
} | 55,956 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
3524,
3724
]
} | 55,957 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
4094,
4325
]
} | 55,958 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// 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.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
4576,
5111
]
} | 55,959 |
NFYE | NFYE.sol | 0x832a784baf6010cce7271528a8613bb8016bb621 | 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);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionStaticCall | function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/ | NatSpecMultiLine | v0.7.0+commit.9e61f92b | None | ipfs://47af30ffb03ea139f02155e935eb810ae3897446e73e9ab54356ebc1500bc53d | {
"func_code_index": [
5291,
5495
]
} | 55,960 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.