Unnamed: 0
int64 0
7.36k
| comments
stringlengths 3
35.2k
| code_string
stringlengths 1
527k
| code
stringlengths 1
527k
| __index_level_0__
int64 0
88.6k
|
|---|---|---|---|---|
115
|
// Implementation of Multi-Token Standard contract /
|
contract ERC1155Base is IERC1155, IERC165, ERC1155Metadata, Ownable, ReentrancyGuard {
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
address constant internal NULL_ADDR = address(0);
string private constant ERR = "ERC1155Base";
// Contract name
string public name;
// Contract symbol
string public symbol;
// ProxyRegistry
address private immutable _proxyRegistry;
// initializer
address private immutable _initializer;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Max mints per transaction
uint256 private _maxTxMint;
// The CAP of mintable tokenIds
uint256 private _cap;
// ETH price of one tokenIds
uint256 private _tokenPrice;
// TokenId counter, 1 minted in ctor
uint256 private _currentTokenId;
// MintAllowed
uint256 mintAllowed;
// Fired when funds are distributed
event Distributed(address indexed receiver, uint256 amount);
/***********************************|
| Initialization |
|__________________________________*/
constructor(address initializer_, address proxyRegistry) {
_proxyRegistry = proxyRegistry;
_initializer = initializer_;
}
function initialize(
address owner_,
string memory name_,
string memory symbol_
) external
{
require(msg.sender == _initializer, ERR);
_transferOwnership(owner_);
name = name_;
symbol = symbol_;
// Mint our first token
balances[owner_][0] = 1;
emit TransferSingle(msg.sender, NULL_ADDR, owner(), 0, 1);
}
/**
* @dev Clone Initialization.
*/
function initialize(
address owner_,
string memory name_,
string memory symbol_,
uint256 cap_,
uint256 maxPerTx_,
uint256 price_) external
{
require(msg.sender == _initializer, ERR);
_transferOwnership(owner_);
name = name_;
symbol = symbol_;
_cap = cap_;
_maxTxMint = maxPerTx_;
_tokenPrice = price_;
// Mint our first token
balances[owner_][0] = 1;
_currentTokenId = 1;
mintAllowed = 1;
emit TransferSingle(msg.sender, NULL_ADDR, owner_, 0, 1);
}
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
external override
{
require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), ERR);
require(_to != address(0), ERR);
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
external override
{
// Requirements
require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), ERR);
require(_to != address(0), ERR);
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
function unsafeBatchMint(address[] calldata _tos, uint256[] calldata _counts, uint256[] calldata _ids) external onlyOwner {
uint256 idOffset = 0;
for (uint256 i = 0; i < _tos.length; ++i) {
uint256 idOffsetEnd = idOffset + _counts[i];
require (idOffsetEnd <= _ids.length, ERR);
{
uint256 curE = _ids[idOffset] >> 8;
uint256 mask = 0;
for (; idOffset < idOffsetEnd; ++idOffset) {
// Update storage balance of previous bin
uint256 elem = _ids[idOffset] >> 8;
uint256 id = uint256(1) << (_ids[idOffset] & 0xFF);
if (elem != curE) {
balances[_tos[i]][curE] |= mask;
curE = elem;
mask = 0;
}
mask |= id;
}
balances[_tos[i]][curE] |= mask;
emit TransferSingle(msg.sender, NULL_ADDR, _tos[i], _ids[idOffset], 1);
}
uint256[] memory amounts = new uint256[](_counts[i]);
for (uint pos = 0; pos < _counts[i]; ++pos)
amounts[pos] = 1;
_callonERC1155BatchReceived(address(0), _tos[i], _ids[idOffsetEnd - _counts[i]:idOffsetEnd], amounts, '');
}
}
function unsafeBatchMessage(address[] calldata _tos, uint256[] calldata _counts, uint256[] calldata _ids) external onlyOwner {
uint256 idOffset = 0;
for (uint256 i = 0; i < _tos.length; ++i) {
uint256 idOffsetEnd = idOffset + _counts[i];
require (idOffsetEnd <= _ids.length, ERR);
for (; idOffset < idOffsetEnd; ++idOffset) {
emit TransferSingle(msg.sender, NULL_ADDR, _tos[i], _ids[idOffset], 1);
}
}
}
/**
* @dev mint
*/
function mint(address to, uint256 numMint) external payable nonReentrant {
uint256 tid = _currentTokenId;
uint256 tidEnd = _currentTokenId + numMint;
require(mintAllowed != 0 &&
numMint > 0 &&
numMint <= _maxTxMint &&
tidEnd <= _cap &&
msg.value >= numMint * _tokenPrice, ERR
);
{
uint256 mask = 0;
uint256 curE = tid >> 8;
for (; tid < tidEnd; ++tid) {
// Update storage balance of previous bin
uint256 elem = tid >> 8;
uint256 id = uint256(1) << (tid & 0xFF);
if (elem != curE) {
balances[to][curE] |= mask;
curE = elem;
mask = 0;
}
mask |= id;
emit TransferSingle(msg.sender, NULL_ADDR, to, tid, 1);
}
balances[to][curE] |= mask;
_currentTokenId += numMint;
}
{
uint256 dust = msg.value - (numMint * _tokenPrice);
if (dust > 0) payable(msg.sender).transfer(dust);
}
{
uint256[] memory ids = new uint256[](numMint);
uint256[] memory amounts = new uint256[](numMint);
for (uint256 i = 0; i < numMint; ++i) {
ids[i] = tid - numMint--;
amounts[i] = 1;
}
_callonERC1155BatchReceived(address(0), to, ids, amounts, '');
}
}
/**
* @dev Distribute rewards
*/
function distribute(
address[] calldata accounts,
uint256[] calldata refunds,
uint256[] calldata percents
) external onlyOwner {
require(
(refunds.length == 0 || refunds.length == accounts.length) &&
(percents.length == 0 || percents.length == accounts.length),
ERR
);
uint256 availableAmount = address(this).balance;
uint256[] memory amounts = new uint256[](accounts.length);
for (uint256 i = 0; i < refunds.length; ++i) {
require(refunds[i] <= availableAmount, ERR);
amounts[i] = refunds[i];
availableAmount -= refunds[i];
}
uint256 amountToShare = availableAmount;
for (uint256 i = 0; i < percents.length; ++i) {
uint256 amount = (amountToShare * percents[i]) / 100;
amounts[i] += (amount <= availableAmount) ? amount : availableAmount;
availableAmount -= amount;
}
for (uint256 i = 0; i < accounts.length; ++i) {
if (amounts[i] > 0) {
payable(accounts[i]).transfer(amounts[i]);
emit Distributed(accounts[i], amounts[i]);
}
}
}
function setBaseMetadataURI(string memory _newBaseMetadataURI) external onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
require(_amount == 1, ERR);
// Update balances
_transferOwner(_from, _to, _id);
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, ERR);
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
uint256 len = _ids.length;
require(len == _amounts.length, ERR);
// Executing all transfers
for (uint256 i = 0; i < len; ++i) {
require(_amounts[i] == 1, ERR);
// Update storage balance of previous bin
_transferOwner(_from, _to, _ids[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, ERR);
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external override
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view override returns (bool isOperator)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistry);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view override returns (uint256)
{
return _isOwner(_owner, _id) ? 1 : 0;
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view override returns (uint256[] memory)
{
require(_owners.length == _ids.length, ERR);
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = _isOwner(_owners[i], _ids[i]) ? 1 : 0;
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external pure override returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
/***********************************|
| balance Functions |
|__________________________________*/
function _isOwner(address _from, uint256 _id) internal view returns (bool) {
return (balances[_from][_id >> 8] & (uint256(1) << (_id & 0xFF))) != 0;
}
function _transferOwner(address _from, address _to, uint256 _id) internal {
uint256 elem = _id >> 8;
uint256 id = uint256(1) << (_id & 0xFF);
if (_from != NULL_ADDR) {
require((balances[_from][elem] & id) != 0, ERR);
balances[_from][elem] &=~id;
}
if (_to != NULL_ADDR) {
balances[_to][elem] |= id;
}
}
}
|
contract ERC1155Base is IERC1155, IERC165, ERC1155Metadata, Ownable, ReentrancyGuard {
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
address constant internal NULL_ADDR = address(0);
string private constant ERR = "ERC1155Base";
// Contract name
string public name;
// Contract symbol
string public symbol;
// ProxyRegistry
address private immutable _proxyRegistry;
// initializer
address private immutable _initializer;
// Objects balances
mapping (address => mapping(uint256 => uint256)) internal balances;
// Operator Functions
mapping (address => mapping(address => bool)) internal operators;
// Max mints per transaction
uint256 private _maxTxMint;
// The CAP of mintable tokenIds
uint256 private _cap;
// ETH price of one tokenIds
uint256 private _tokenPrice;
// TokenId counter, 1 minted in ctor
uint256 private _currentTokenId;
// MintAllowed
uint256 mintAllowed;
// Fired when funds are distributed
event Distributed(address indexed receiver, uint256 amount);
/***********************************|
| Initialization |
|__________________________________*/
constructor(address initializer_, address proxyRegistry) {
_proxyRegistry = proxyRegistry;
_initializer = initializer_;
}
function initialize(
address owner_,
string memory name_,
string memory symbol_
) external
{
require(msg.sender == _initializer, ERR);
_transferOwnership(owner_);
name = name_;
symbol = symbol_;
// Mint our first token
balances[owner_][0] = 1;
emit TransferSingle(msg.sender, NULL_ADDR, owner(), 0, 1);
}
/**
* @dev Clone Initialization.
*/
function initialize(
address owner_,
string memory name_,
string memory symbol_,
uint256 cap_,
uint256 maxPerTx_,
uint256 price_) external
{
require(msg.sender == _initializer, ERR);
_transferOwnership(owner_);
name = name_;
symbol = symbol_;
_cap = cap_;
_maxTxMint = maxPerTx_;
_tokenPrice = price_;
// Mint our first token
balances[owner_][0] = 1;
_currentTokenId = 1;
mintAllowed = 1;
emit TransferSingle(msg.sender, NULL_ADDR, owner_, 0, 1);
}
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
external override
{
require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), ERR);
require(_to != address(0), ERR);
_safeTransferFrom(_from, _to, _id, _amount);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
external override
{
// Requirements
require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), ERR);
require(_to != address(0), ERR);
_safeBatchTransferFrom(_from, _to, _ids, _amounts);
_callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data);
}
function unsafeBatchMint(address[] calldata _tos, uint256[] calldata _counts, uint256[] calldata _ids) external onlyOwner {
uint256 idOffset = 0;
for (uint256 i = 0; i < _tos.length; ++i) {
uint256 idOffsetEnd = idOffset + _counts[i];
require (idOffsetEnd <= _ids.length, ERR);
{
uint256 curE = _ids[idOffset] >> 8;
uint256 mask = 0;
for (; idOffset < idOffsetEnd; ++idOffset) {
// Update storage balance of previous bin
uint256 elem = _ids[idOffset] >> 8;
uint256 id = uint256(1) << (_ids[idOffset] & 0xFF);
if (elem != curE) {
balances[_tos[i]][curE] |= mask;
curE = elem;
mask = 0;
}
mask |= id;
}
balances[_tos[i]][curE] |= mask;
emit TransferSingle(msg.sender, NULL_ADDR, _tos[i], _ids[idOffset], 1);
}
uint256[] memory amounts = new uint256[](_counts[i]);
for (uint pos = 0; pos < _counts[i]; ++pos)
amounts[pos] = 1;
_callonERC1155BatchReceived(address(0), _tos[i], _ids[idOffsetEnd - _counts[i]:idOffsetEnd], amounts, '');
}
}
function unsafeBatchMessage(address[] calldata _tos, uint256[] calldata _counts, uint256[] calldata _ids) external onlyOwner {
uint256 idOffset = 0;
for (uint256 i = 0; i < _tos.length; ++i) {
uint256 idOffsetEnd = idOffset + _counts[i];
require (idOffsetEnd <= _ids.length, ERR);
for (; idOffset < idOffsetEnd; ++idOffset) {
emit TransferSingle(msg.sender, NULL_ADDR, _tos[i], _ids[idOffset], 1);
}
}
}
/**
* @dev mint
*/
function mint(address to, uint256 numMint) external payable nonReentrant {
uint256 tid = _currentTokenId;
uint256 tidEnd = _currentTokenId + numMint;
require(mintAllowed != 0 &&
numMint > 0 &&
numMint <= _maxTxMint &&
tidEnd <= _cap &&
msg.value >= numMint * _tokenPrice, ERR
);
{
uint256 mask = 0;
uint256 curE = tid >> 8;
for (; tid < tidEnd; ++tid) {
// Update storage balance of previous bin
uint256 elem = tid >> 8;
uint256 id = uint256(1) << (tid & 0xFF);
if (elem != curE) {
balances[to][curE] |= mask;
curE = elem;
mask = 0;
}
mask |= id;
emit TransferSingle(msg.sender, NULL_ADDR, to, tid, 1);
}
balances[to][curE] |= mask;
_currentTokenId += numMint;
}
{
uint256 dust = msg.value - (numMint * _tokenPrice);
if (dust > 0) payable(msg.sender).transfer(dust);
}
{
uint256[] memory ids = new uint256[](numMint);
uint256[] memory amounts = new uint256[](numMint);
for (uint256 i = 0; i < numMint; ++i) {
ids[i] = tid - numMint--;
amounts[i] = 1;
}
_callonERC1155BatchReceived(address(0), to, ids, amounts, '');
}
}
/**
* @dev Distribute rewards
*/
function distribute(
address[] calldata accounts,
uint256[] calldata refunds,
uint256[] calldata percents
) external onlyOwner {
require(
(refunds.length == 0 || refunds.length == accounts.length) &&
(percents.length == 0 || percents.length == accounts.length),
ERR
);
uint256 availableAmount = address(this).balance;
uint256[] memory amounts = new uint256[](accounts.length);
for (uint256 i = 0; i < refunds.length; ++i) {
require(refunds[i] <= availableAmount, ERR);
amounts[i] = refunds[i];
availableAmount -= refunds[i];
}
uint256 amountToShare = availableAmount;
for (uint256 i = 0; i < percents.length; ++i) {
uint256 amount = (amountToShare * percents[i]) / 100;
amounts[i] += (amount <= availableAmount) ? amount : availableAmount;
availableAmount -= amount;
}
for (uint256 i = 0; i < accounts.length; ++i) {
if (amounts[i] > 0) {
payable(accounts[i]).transfer(amounts[i]);
emit Distributed(accounts[i], amounts[i]);
}
}
}
function setBaseMetadataURI(string memory _newBaseMetadataURI) external onlyOwner {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount)
internal
{
require(_amount == 1, ERR);
// Update balances
_transferOwner(_from, _to, _id);
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data)
internal
{
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data);
require(retval == ERC1155_RECEIVED_VALUE, ERR);
}
}
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
*/
function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts)
internal
{
uint256 len = _ids.length;
require(len == _amounts.length, ERR);
// Executing all transfers
for (uint256 i = 0; i < len; ++i) {
require(_amounts[i] == 1, ERR);
// Update storage balance of previous bin
_transferOwner(_from, _to, _ids[i]);
}
// Emit event
emit TransferBatch(msg.sender, _from, _to, _ids, _amounts);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
internal
{
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data);
require(retval == ERC1155_BATCH_RECEIVED_VALUE, ERR);
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved)
external override
{
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public view override returns (bool isOperator)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistry);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public view override returns (uint256)
{
return _isOwner(_owner, _id) ? 1 : 0;
}
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public view override returns (uint256[] memory)
{
require(_owners.length == _ids.length, ERR);
// Variables
uint256[] memory batchBalances = new uint256[](_owners.length);
// Iterate over each owner and token ID
for (uint256 i = 0; i < _owners.length; i++) {
batchBalances[i] = _isOwner(_owners[i], _ids[i]) ? 1 : 0;
}
return batchBalances;
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID) external pure override returns (bool) {
if (_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155) {
return true;
}
return false;
}
/***********************************|
| balance Functions |
|__________________________________*/
function _isOwner(address _from, uint256 _id) internal view returns (bool) {
return (balances[_from][_id >> 8] & (uint256(1) << (_id & 0xFF))) != 0;
}
function _transferOwner(address _from, address _to, uint256 _id) internal {
uint256 elem = _id >> 8;
uint256 id = uint256(1) << (_id & 0xFF);
if (_from != NULL_ADDR) {
require((balances[_from][elem] & id) != 0, ERR);
balances[_from][elem] &=~id;
}
if (_to != NULL_ADDR) {
balances[_to][elem] |= id;
}
}
}
| 20,450
|
22
|
// Need to adjust for decimals of collateral
|
uint256 PUSD_amount_precision = PUSD_amount.div(10 ** missing_decimals);
(uint256 collateral_needed) = PusdPoolLibrary.calcRedeem1t1PUSD(
getCollateralPrice(),
PUSD_amount_precision,
0
);
require(collateral_needed <= collateral_token.balanceOf(address(this)), "Not enough collateral in pool");
|
uint256 PUSD_amount_precision = PUSD_amount.div(10 ** missing_decimals);
(uint256 collateral_needed) = PusdPoolLibrary.calcRedeem1t1PUSD(
getCollateralPrice(),
PUSD_amount_precision,
0
);
require(collateral_needed <= collateral_token.balanceOf(address(this)), "Not enough collateral in pool");
| 32,069
|
3
|
// transfers ETH or tokens to self custody./selfCustodyAccount Address of the target account./token Address of the target token./amount Number of tokens./ return shortfall Number of GRG pool operator shortfall.
|
function transferToSelfCustody(
address payable selfCustodyAccount,
address token,
uint256 amount
) external returns (uint256 shortfall);
|
function transferToSelfCustody(
address payable selfCustodyAccount,
address token,
uint256 amount
) external returns (uint256 shortfall);
| 26,843
|
53
|
// Submit a hashed secret of the rating for work in task `_id` which was performed by user with task role id `_role`./ Allowed within 5 days period starting which whichever is first from either the deliverable being submitted or the dueDate been reached./ Allowed only for evaluator to rate worker and for worker to rate manager performance./ Once submitted ratings can not be changed or overwritten./_id Id of the task/_role Id of the role, as defined in TaskRole enum/_ratingSecret `keccak256` hash of a salt and 0-50 rating score (in increments of 10, .e.g 0, 10, 20, 30, 40 or 50)./
|
function submitTaskWorkRating(uint256 _id, uint8 _role, bytes32 _ratingSecret) public;
|
function submitTaskWorkRating(uint256 _id, uint8 _role, bytes32 _ratingSecret) public;
| 3,492
|
38
|
// 获取奖励代币
|
function GetReward(uint256 eventId) public
|
function GetReward(uint256 eventId) public
| 18,641
|
281
|
// Set the starting index block for the collection, essentially unblocking setting starting index
|
function emergencySetStartingIndex() public onlyOwner{
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
|
function emergencySetStartingIndex() public onlyOwner{
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
| 21,462
|
204
|
// Cant send tokens to the zero address.
|
if (_beneficiary == address(0)) revert PAY_TO_ZERO_ADDRESS();
|
if (_beneficiary == address(0)) revert PAY_TO_ZERO_ADDRESS();
| 14,403
|
176
|
// if sell, multiply by 1.2
|
if(automatedMarketMakerPairs[to]) {
fees = fees.mul(sellFeeIncreaseFactor).div(100);
}
|
if(automatedMarketMakerPairs[to]) {
fees = fees.mul(sellFeeIncreaseFactor).div(100);
}
| 35,380
|
17
|
// Claim all rewards from caller into a given address
|
function claim(address to)
external
returns (uint256 claiming);
|
function claim(address to)
external
returns (uint256 claiming);
| 28,282
|
44
|
// Handle when collateral is eth
|
if (collateral == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE){
|
if (collateral == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE){
| 19,340
|
57
|
// nami presale contract
|
address public namiPresale;
|
address public namiPresale;
| 17,161
|
72
|
// The execution phase. tos The handlers of combo. datas The combo datas. /
|
function _execs(address[] memory tos, bytes[] memory datas) internal {
require(
tos.length == datas.length,
"Tos and datas length inconsistent"
);
for (uint256 i = 0; i < tos.length; i++) {
_exec(tos[i], datas[i]);
// Setup the process to be triggered in the post-process phase
_setPostProcess(tos[i]);
}
}
|
function _execs(address[] memory tos, bytes[] memory datas) internal {
require(
tos.length == datas.length,
"Tos and datas length inconsistent"
);
for (uint256 i = 0; i < tos.length; i++) {
_exec(tos[i], datas[i]);
// Setup the process to be triggered in the post-process phase
_setPostProcess(tos[i]);
}
}
| 4,050
|
133
|
// Variables//Events//This function allows the user to map the tellor's Id to it's _adjFactor and to match the standarized granularity_tellorId uint the tellor status_adjFactor is 1eN where N is the number of decimals to convert to ADO standard/
|
function defineTellorIdtoAdjFactor(uint _tellorId, int _adjFactor) external{
require(tellorIdtoAdjFactor[_tellorId] == 0, "Already Set");
tellorIdtoAdjFactor[_tellorId] = _adjFactor;
emit AdjFactorMapped(_tellorId, _adjFactor);
}
|
function defineTellorIdtoAdjFactor(uint _tellorId, int _adjFactor) external{
require(tellorIdtoAdjFactor[_tellorId] == 0, "Already Set");
tellorIdtoAdjFactor[_tellorId] = _adjFactor;
emit AdjFactorMapped(_tellorId, _adjFactor);
}
| 2,339
|
0
|
// Keep track of the participants These can have token transfers, hence they are declared as [payable]
|
address payable[] public participants;
address payable public recentWinner;
uint256 randomness;
uint256 minimumUSD;
|
address payable[] public participants;
address payable public recentWinner;
uint256 randomness;
uint256 minimumUSD;
| 36,476
|
5
|
// Store the items in a set with a specific rarity [common, uncommon, rare, epic, legendary]/e.g., itemSetByRarity[itemSet][rarity]->[Item Struct]
|
mapping (uint256 => mapping (uint256 => Item[])) private itemSetByRarity;
|
mapping (uint256 => mapping (uint256 => Item[])) private itemSetByRarity;
| 20,978
|
329
|
// If we have a depositReceipt on the same round, BUT we have some unredeemed shares we debit from the unredeemedShares, but leave the amount field intact If the round has past, with no new deposits, we just zero it out for new deposits.
|
if (depositReceipt.round < currentRound) {
depositReceipts[msg.sender].amount = 0;
}
|
if (depositReceipt.round < currentRound) {
depositReceipts[msg.sender].amount = 0;
}
| 71,220
|
15
|
// Get the timestamp and publisher for that block.
|
(uint256 timestamp, address publisher) = abi.decode(_postStateRootBatchHeader.extraData, (uint256, address));
|
(uint256 timestamp, address publisher) = abi.decode(_postStateRootBatchHeader.extraData, (uint256, address));
| 12,806
|
120
|
// withdraw a specified amount from a lock. _index and _lockID ensure the correct lock is changedthis prevents errors when a user performs multiple tx per block possibly with varying gas prices /
|
function withdraw(
address _lpToken,
uint256 _index,
uint256 _lockID,
uint256 _amount
|
function withdraw(
address _lpToken,
uint256 _index,
uint256 _lockID,
uint256 _amount
| 36,297
|
18
|
// Genesis block must be at or before the current block
|
require(_genesisBlock <= block.number);
|
require(_genesisBlock <= block.number);
| 10,193
|
106
|
// high
|
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
|
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
| 7,665
|
192
|
// Function to vote during a board meeting/_boardMeetingID The index of the board meeting/_supportsProposal True if the proposal is supported
|
function vote(
uint _boardMeetingID,
bool _supportsProposal
);
|
function vote(
uint _boardMeetingID,
bool _supportsProposal
);
| 45,567
|
271
|
// Assert length of <b> is valid, given length of nested bytes
|
require(
b.length >= index + nestedBytesLength,
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
|
require(
b.length >= index + nestedBytesLength,
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
| 20,284
|
9
|
// max mine joys per day
|
uint256 public constant MAX_REWARD_JOYS_PER_DAY = 20000;
|
uint256 public constant MAX_REWARD_JOYS_PER_DAY = 20000;
| 33,452
|
71
|
// Accept ethers to buy tokens during the token saleMinimium holdings to receive a VIP rank is 24000 LooksCoin /
|
function buyTokens() payable returns (uint256 amount)
|
function buyTokens() payable returns (uint256 amount)
| 25,416
|
315
|
// updates the redirected balance of the user. If the user is not redirecting his interest, nothing is executed._user the address of the user for which the interest is being accumulated_balanceToAdd the amount to add to the redirected balance_balanceToRemove the amount to remove from the redirected balance/
|
) internal {
address redirectionAddress = interestRedirectionAddresses[_user];
//if there isn't any redirection, nothing to be done
if(redirectionAddress == address(0)){
return;
}
//compound balances of the redirected address
(,,uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress);
//updating the redirected balance
redirectedBalances[redirectionAddress] = redirectedBalances[redirectionAddress]
.add(_balanceToAdd)
.sub(_balanceToRemove);
//if the interest of redirectionAddress is also being redirected, we need to update
//the redirected balance of the redirection target by adding the balance increase
address targetOfRedirectionAddress = interestRedirectionAddresses[redirectionAddress];
if(targetOfRedirectionAddress != address(0)){
redirectedBalances[targetOfRedirectionAddress] = redirectedBalances[targetOfRedirectionAddress].add(balanceIncrease);
}
emit RedirectedBalanceUpdated(
redirectionAddress,
balanceIncrease,
index,
_balanceToAdd,
_balanceToRemove
);
}
|
) internal {
address redirectionAddress = interestRedirectionAddresses[_user];
//if there isn't any redirection, nothing to be done
if(redirectionAddress == address(0)){
return;
}
//compound balances of the redirected address
(,,uint256 balanceIncrease, uint256 index) = cumulateBalanceInternal(redirectionAddress);
//updating the redirected balance
redirectedBalances[redirectionAddress] = redirectedBalances[redirectionAddress]
.add(_balanceToAdd)
.sub(_balanceToRemove);
//if the interest of redirectionAddress is also being redirected, we need to update
//the redirected balance of the redirection target by adding the balance increase
address targetOfRedirectionAddress = interestRedirectionAddresses[redirectionAddress];
if(targetOfRedirectionAddress != address(0)){
redirectedBalances[targetOfRedirectionAddress] = redirectedBalances[targetOfRedirectionAddress].add(balanceIncrease);
}
emit RedirectedBalanceUpdated(
redirectionAddress,
balanceIncrease,
index,
_balanceToAdd,
_balanceToRemove
);
}
| 18,627
|
284
|
// GET ALL PIG OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH
|
function pigNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new string[](0);
} else {
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = pigNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
|
function pigNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new string[](0);
} else {
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = pigNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
| 67,314
|
63
|
// Return the total amount of tokens allocated to subgraph. _subgraphDeploymentID Address used as the allocation identifierreturn Total tokens allocated to subgraph /
|
function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID)
external
override
view
returns (uint256)
|
function getSubgraphAllocatedTokens(bytes32 _subgraphDeploymentID)
external
override
view
returns (uint256)
| 20,596
|
4
|
// amount withdrawn per interval
|
uint256 public withdrawAmount;
|
uint256 public withdrawAmount;
| 7,429
|
4
|
// get own token balance
|
uint input = sourceToken.balanceOf(address(this));
if (input == 0){
revert("i");
}
|
uint input = sourceToken.balanceOf(address(this));
if (input == 0){
revert("i");
}
| 39,541
|
2
|
// 回退函数
|
function () public payable{}
}
|
function () public payable{}
}
| 13,066
|
359
|
// Struct storing variables used in calculations in the
|
// {add,remove}Liquidity functions to avoid stack too deep errors
struct ManageLiquidityInfo {
uint256 d0;
uint256 d1;
uint256 d2;
uint256 preciseA;
LPToken lpToken;
uint256 totalSupply;
uint256[] balances;
uint256[] multipliers;
}
|
// {add,remove}Liquidity functions to avoid stack too deep errors
struct ManageLiquidityInfo {
uint256 d0;
uint256 d1;
uint256 d2;
uint256 preciseA;
LPToken lpToken;
uint256 totalSupply;
uint256[] balances;
uint256[] multipliers;
}
| 64,744
|
71
|
// Getters
|
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
|
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
| 11,151
|
51
|
// Lazy Payable Claim manifold.xyz Lazy claim with optional whitelist ERC1155 tokens /
|
contract ERC1155LazyPayableClaim is IERC165, IERC1155LazyPayableClaim, ICreatorExtensionTokenURI, LazyPayableClaim {
using Strings for uint256;
// stores mapping from contractAddress/instanceId to the claim it represents
// { contractAddress => { instanceId => Claim } }
mapping(address => mapping(uint256 => Claim)) private _claims;
// { contractAddress => { tokenId => { instanceId } }
mapping(address => mapping(uint256 => uint256)) private _claimTokenIds;
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AdminControl) returns (bool) {
return interfaceId == type(IERC1155LazyPayableClaim).interfaceId ||
interfaceId == type(ILazyPayableClaim).interfaceId ||
interfaceId == type(ICreatorExtensionTokenURI).interfaceId ||
interfaceId == type(IAdminControl).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
constructor(address delegationRegistry) LazyPayableClaim(delegationRegistry) {}
/**
* See {IERC1155LazyClaim-initializeClaim}.
*/
function initializeClaim(
address creatorContractAddress,
uint256 instanceId,
ClaimParameters calldata claimParameters
) external override creatorAdminRequired(creatorContractAddress) {
// Revert if claim at instanceId already exists
require(_claims[creatorContractAddress][instanceId].storageProtocol == StorageProtocol.INVALID, "Claim already initialized");
// Sanity checks
require(claimParameters.storageProtocol != StorageProtocol.INVALID, "Cannot initialize with invalid storage protocol");
require(claimParameters.endDate == 0 || claimParameters.startDate < claimParameters.endDate, "Cannot have startDate greater than or equal to endDate");
require(claimParameters.merkleRoot == "" || claimParameters.walletMax == 0, "Cannot provide both walletMax and merkleRoot");
address[] memory receivers = new address[](1);
receivers[0] = msg.sender;
string[] memory uris = new string[](1);
uint256[] memory amounts = new uint256[](1);
uint256[] memory newTokenIds = IERC1155CreatorCore(creatorContractAddress).mintExtensionNew(receivers, amounts, uris);
// Create the claim
_claims[creatorContractAddress][instanceId] = Claim({
total: 0,
totalMax: claimParameters.totalMax,
walletMax: claimParameters.walletMax,
startDate: claimParameters.startDate,
endDate: claimParameters.endDate,
storageProtocol: claimParameters.storageProtocol,
merkleRoot: claimParameters.merkleRoot,
location: claimParameters.location,
tokenId: newTokenIds[0],
cost: claimParameters.cost,
paymentReceiver: claimParameters.paymentReceiver,
erc20: claimParameters.erc20
});
_claimTokenIds[creatorContractAddress][newTokenIds[0]] = instanceId;
emit ClaimInitialized(creatorContractAddress, instanceId, msg.sender);
}
/**
* See {IERC1155LazyClaim-updateClaim}.
*/
function updateClaim(
address creatorContractAddress,
uint256 instanceId,
ClaimParameters memory claimParameters
) external override creatorAdminRequired(creatorContractAddress) {
Claim memory claim = _claims[creatorContractAddress][instanceId];
require(claim.storageProtocol != StorageProtocol.INVALID, "Claim not initialized");
require(claimParameters.storageProtocol != StorageProtocol.INVALID, "Cannot set invalid storage protocol");
require(claimParameters.endDate == 0 || claimParameters.startDate < claimParameters.endDate, "Cannot have startDate greater than or equal to endDate");
require(claimParameters.erc20 == claim.erc20, "Cannot change payment token");
if (claimParameters.totalMax != 0 && claim.total > claimParameters.totalMax) {
claimParameters.totalMax = claim.total;
}
// Overwrite the existing claim
_claims[creatorContractAddress][instanceId] = Claim({
total: claim.total,
totalMax: claimParameters.totalMax,
walletMax: claimParameters.walletMax,
startDate: claimParameters.startDate,
endDate: claimParameters.endDate,
storageProtocol: claimParameters.storageProtocol,
merkleRoot: claimParameters.merkleRoot,
location: claimParameters.location,
tokenId: claim.tokenId,
cost: claimParameters.cost,
paymentReceiver: claimParameters.paymentReceiver,
erc20: claimParameters.erc20
});
emit ClaimUpdated(creatorContractAddress, instanceId);
}
/**
* See {IERC1155LazyClaim-updateTokenURIParams}.
*/
function updateTokenURIParams(
address creatorContractAddress, uint256 instanceId,
StorageProtocol storageProtocol,
string calldata location
) external override creatorAdminRequired(creatorContractAddress) {
Claim storage claim = _claims[creatorContractAddress][instanceId];
require(claim.storageProtocol != StorageProtocol.INVALID, "Claim not initialized");
require(storageProtocol != StorageProtocol.INVALID, "Cannot set invalid storage protocol");
claim.storageProtocol = storageProtocol;
claim.location = location;
emit ClaimUpdated(creatorContractAddress, instanceId);
}
/**
* See {IERC1155LazyClaim-extendTokenURI}.
*/
function extendTokenURI(
address creatorContractAddress, uint256 instanceId,
string calldata locationChunk
) external override creatorAdminRequired(creatorContractAddress) {
Claim storage claim = _claims[creatorContractAddress][instanceId];
require(claim.storageProtocol == StorageProtocol.NONE, "Invalid storage protocol");
claim.location = string(abi.encodePacked(claim.location, locationChunk));
}
/**
* See {IERC1155LazyClaim-getClaim}.
*/
function getClaim(address creatorContractAddress, uint256 instanceId) public override view returns(Claim memory claim) {
return _getClaim(creatorContractAddress, instanceId);
}
/**
* See {IERC1155LazyClaim-getClaimForToken}.
*/
function getClaimForToken(address creatorContractAddress, uint256 tokenId) external override view returns(uint256 instanceId, Claim memory claim) {
instanceId = _claimTokenIds[creatorContractAddress][tokenId];
claim = _getClaim(creatorContractAddress, instanceId);
}
function _getClaim(address creatorContractAddress, uint256 instanceId) private view returns(Claim storage claim) {
claim = _claims[creatorContractAddress][instanceId];
require(claim.storageProtocol != StorageProtocol.INVALID, "Claim not initialized");
}
/**
* See {ILazyPayableClaim-checkMintIndex}.
*/
function checkMintIndex(address creatorContractAddress, uint256 instanceId, uint32 mintIndex) external override view returns(bool) {
Claim memory claim = getClaim(creatorContractAddress, instanceId);
return _checkMintIndex(creatorContractAddress, instanceId, claim.merkleRoot, mintIndex);
}
/**
* See {ILazyPayableClaim-checkMintIndices}.
*/
function checkMintIndices(address creatorContractAddress, uint256 instanceId, uint32[] calldata mintIndices) external override view returns(bool[] memory minted) {
Claim memory claim = getClaim(creatorContractAddress, instanceId);
uint256 mintIndicesLength = mintIndices.length;
minted = new bool[](mintIndices.length);
for (uint256 i; i < mintIndicesLength;) {
minted[i] = _checkMintIndex(creatorContractAddress, instanceId, claim.merkleRoot, mintIndices[i]);
unchecked{ ++i; }
}
}
/**
* See {ILazyPayableClaim-getTotalMints}.
*/
function getTotalMints(address minter, address creatorContractAddress, uint256 instanceId) external override view returns(uint32) {
Claim memory claim = getClaim(creatorContractAddress, instanceId);
return _getTotalMints(claim.walletMax, minter, creatorContractAddress, instanceId);
}
/**
* See {ILazyPayableClaim-mint}.
*/
function mint(address creatorContractAddress, uint256 instanceId, uint32 mintIndex, bytes32[] calldata merkleProof, address mintFor) external payable override {
Claim storage claim = _getClaim(creatorContractAddress, instanceId);
// Check totalMax
require(++claim.total <= claim.totalMax || claim.totalMax == 0, "Maximum tokens already minted for this claim");
// Validate mint
_validateMint(creatorContractAddress, instanceId, claim.startDate, claim.endDate, claim.walletMax, claim.merkleRoot, mintIndex, merkleProof, mintFor);
// Transfer funds
_transferFunds(claim.erc20, claim.cost, claim.paymentReceiver, 1, claim.merkleRoot != "");
// Do mint
address[] memory recipients = new address[](1);
recipients[0] = msg.sender;
uint256[] memory amounts = new uint256[](1);
amounts[0] = 1;
_mintClaim(creatorContractAddress, claim, recipients, amounts);
emit ClaimMint(creatorContractAddress, instanceId);
}
/**
* See {ILazyPayableClaim-mintBatch}.
*/
function mintBatch(address creatorContractAddress, uint256 instanceId, uint16 mintCount, uint32[] calldata mintIndices, bytes32[][] calldata merkleProofs, address mintFor) external payable override {
Claim storage claim = _getClaim(creatorContractAddress, instanceId);
// Check totalMax
claim.total += mintCount;
require(claim.totalMax == 0 || claim.total <= claim.totalMax, "Too many requested for this claim");
// Validate mint
_validateMint(creatorContractAddress, instanceId, claim.startDate, claim.endDate, claim.walletMax, claim.merkleRoot, mintCount, mintIndices, merkleProofs, mintFor);
// Transfer funds
_transferFunds(claim.erc20, claim.cost, claim.paymentReceiver, mintCount, claim.merkleRoot != "");
// Do mint
address[] memory recipients = new address[](1);
recipients[0] = msg.sender;
uint256[] memory amounts = new uint256[](1);
amounts[0] = mintCount;
_mintClaim(creatorContractAddress, claim, recipients, amounts);
emit ClaimMintBatch(creatorContractAddress, instanceId, mintCount);
}
/**
* See {ILazyPayableClaim-mintProxy}.
*/
function mintProxy(address creatorContractAddress, uint256 instanceId, uint16 mintCount, uint32[] calldata mintIndices, bytes32[][] calldata merkleProofs, address mintFor) external payable override {
Claim storage claim = _getClaim(creatorContractAddress, instanceId);
// Check totalMax
claim.total += mintCount;
require(claim.totalMax == 0 || claim.total <= claim.totalMax, "Too many requested for this claim");
// Validate mint
_validateMintProxy(creatorContractAddress, instanceId, claim.startDate, claim.endDate, claim.walletMax, claim.merkleRoot, mintCount, mintIndices, merkleProofs, mintFor);
// Transfer funds
_transferFundsProxy(claim.erc20, claim.cost, claim.paymentReceiver, mintCount, claim.merkleRoot != "");
// Do mint
address[] memory recipients = new address[](1);
recipients[0] = mintFor;
uint256[] memory amounts = new uint256[](1);
amounts[0] = mintCount;
_mintClaim(creatorContractAddress, claim, recipients, amounts);
emit ClaimMintProxy(creatorContractAddress, instanceId, mintCount, msg.sender, mintFor);
}
/**
* See {IERC1155LazyPayableClaim-airdrop}.
*/
function airdrop(address creatorContractAddress, uint256 instanceId, address[] calldata recipients,
uint256[] calldata amounts) external override creatorAdminRequired(creatorContractAddress) {
require(recipients.length == amounts.length, "Unequal number of recipients and amounts provided");
// Fetch the claim
Claim storage claim = _claims[creatorContractAddress][instanceId];
uint256 totalAmount;
for (uint256 i; i < amounts.length;) {
totalAmount += amounts[i];
unchecked{ ++i; }
}
require(totalAmount <= MAX_UINT_32, "Too many requested");
claim.total += uint32(totalAmount);
if (claim.totalMax != 0 && claim.total > claim.totalMax) {
claim.totalMax = claim.total;
}
// Airdrop the tokens
_mintClaim(creatorContractAddress, claim, recipients, amounts);
}
/**
* Mint a claim
*/
function _mintClaim(address creatorContractAddress, Claim storage claim, address[] memory recipients, uint256[] memory amounts) private {
uint256[] memory tokenIds = new uint256[](1);
tokenIds[0] = claim.tokenId;
IERC1155CreatorCore(creatorContractAddress).mintExtensionExisting(recipients, tokenIds, amounts);
}
/**
* See {ICreatorExtensionTokenURI-tokenURI}.
*/
function tokenURI(address creatorContractAddress, uint256 tokenId) external override view returns(string memory uri) {
uint224 tokenClaim = uint224(_claimTokenIds[creatorContractAddress][tokenId]);
require(tokenClaim > 0, "Token does not exist");
Claim memory claim = _claims[creatorContractAddress][tokenClaim];
string memory prefix = "";
if (claim.storageProtocol == StorageProtocol.ARWEAVE) {
prefix = ARWEAVE_PREFIX;
} else if (claim.storageProtocol == StorageProtocol.IPFS) {
prefix = IPFS_PREFIX;
}
uri = string(abi.encodePacked(prefix, claim.location));
}
}
|
contract ERC1155LazyPayableClaim is IERC165, IERC1155LazyPayableClaim, ICreatorExtensionTokenURI, LazyPayableClaim {
using Strings for uint256;
// stores mapping from contractAddress/instanceId to the claim it represents
// { contractAddress => { instanceId => Claim } }
mapping(address => mapping(uint256 => Claim)) private _claims;
// { contractAddress => { tokenId => { instanceId } }
mapping(address => mapping(uint256 => uint256)) private _claimTokenIds;
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AdminControl) returns (bool) {
return interfaceId == type(IERC1155LazyPayableClaim).interfaceId ||
interfaceId == type(ILazyPayableClaim).interfaceId ||
interfaceId == type(ICreatorExtensionTokenURI).interfaceId ||
interfaceId == type(IAdminControl).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
constructor(address delegationRegistry) LazyPayableClaim(delegationRegistry) {}
/**
* See {IERC1155LazyClaim-initializeClaim}.
*/
function initializeClaim(
address creatorContractAddress,
uint256 instanceId,
ClaimParameters calldata claimParameters
) external override creatorAdminRequired(creatorContractAddress) {
// Revert if claim at instanceId already exists
require(_claims[creatorContractAddress][instanceId].storageProtocol == StorageProtocol.INVALID, "Claim already initialized");
// Sanity checks
require(claimParameters.storageProtocol != StorageProtocol.INVALID, "Cannot initialize with invalid storage protocol");
require(claimParameters.endDate == 0 || claimParameters.startDate < claimParameters.endDate, "Cannot have startDate greater than or equal to endDate");
require(claimParameters.merkleRoot == "" || claimParameters.walletMax == 0, "Cannot provide both walletMax and merkleRoot");
address[] memory receivers = new address[](1);
receivers[0] = msg.sender;
string[] memory uris = new string[](1);
uint256[] memory amounts = new uint256[](1);
uint256[] memory newTokenIds = IERC1155CreatorCore(creatorContractAddress).mintExtensionNew(receivers, amounts, uris);
// Create the claim
_claims[creatorContractAddress][instanceId] = Claim({
total: 0,
totalMax: claimParameters.totalMax,
walletMax: claimParameters.walletMax,
startDate: claimParameters.startDate,
endDate: claimParameters.endDate,
storageProtocol: claimParameters.storageProtocol,
merkleRoot: claimParameters.merkleRoot,
location: claimParameters.location,
tokenId: newTokenIds[0],
cost: claimParameters.cost,
paymentReceiver: claimParameters.paymentReceiver,
erc20: claimParameters.erc20
});
_claimTokenIds[creatorContractAddress][newTokenIds[0]] = instanceId;
emit ClaimInitialized(creatorContractAddress, instanceId, msg.sender);
}
/**
* See {IERC1155LazyClaim-updateClaim}.
*/
function updateClaim(
address creatorContractAddress,
uint256 instanceId,
ClaimParameters memory claimParameters
) external override creatorAdminRequired(creatorContractAddress) {
Claim memory claim = _claims[creatorContractAddress][instanceId];
require(claim.storageProtocol != StorageProtocol.INVALID, "Claim not initialized");
require(claimParameters.storageProtocol != StorageProtocol.INVALID, "Cannot set invalid storage protocol");
require(claimParameters.endDate == 0 || claimParameters.startDate < claimParameters.endDate, "Cannot have startDate greater than or equal to endDate");
require(claimParameters.erc20 == claim.erc20, "Cannot change payment token");
if (claimParameters.totalMax != 0 && claim.total > claimParameters.totalMax) {
claimParameters.totalMax = claim.total;
}
// Overwrite the existing claim
_claims[creatorContractAddress][instanceId] = Claim({
total: claim.total,
totalMax: claimParameters.totalMax,
walletMax: claimParameters.walletMax,
startDate: claimParameters.startDate,
endDate: claimParameters.endDate,
storageProtocol: claimParameters.storageProtocol,
merkleRoot: claimParameters.merkleRoot,
location: claimParameters.location,
tokenId: claim.tokenId,
cost: claimParameters.cost,
paymentReceiver: claimParameters.paymentReceiver,
erc20: claimParameters.erc20
});
emit ClaimUpdated(creatorContractAddress, instanceId);
}
/**
* See {IERC1155LazyClaim-updateTokenURIParams}.
*/
function updateTokenURIParams(
address creatorContractAddress, uint256 instanceId,
StorageProtocol storageProtocol,
string calldata location
) external override creatorAdminRequired(creatorContractAddress) {
Claim storage claim = _claims[creatorContractAddress][instanceId];
require(claim.storageProtocol != StorageProtocol.INVALID, "Claim not initialized");
require(storageProtocol != StorageProtocol.INVALID, "Cannot set invalid storage protocol");
claim.storageProtocol = storageProtocol;
claim.location = location;
emit ClaimUpdated(creatorContractAddress, instanceId);
}
/**
* See {IERC1155LazyClaim-extendTokenURI}.
*/
function extendTokenURI(
address creatorContractAddress, uint256 instanceId,
string calldata locationChunk
) external override creatorAdminRequired(creatorContractAddress) {
Claim storage claim = _claims[creatorContractAddress][instanceId];
require(claim.storageProtocol == StorageProtocol.NONE, "Invalid storage protocol");
claim.location = string(abi.encodePacked(claim.location, locationChunk));
}
/**
* See {IERC1155LazyClaim-getClaim}.
*/
function getClaim(address creatorContractAddress, uint256 instanceId) public override view returns(Claim memory claim) {
return _getClaim(creatorContractAddress, instanceId);
}
/**
* See {IERC1155LazyClaim-getClaimForToken}.
*/
function getClaimForToken(address creatorContractAddress, uint256 tokenId) external override view returns(uint256 instanceId, Claim memory claim) {
instanceId = _claimTokenIds[creatorContractAddress][tokenId];
claim = _getClaim(creatorContractAddress, instanceId);
}
function _getClaim(address creatorContractAddress, uint256 instanceId) private view returns(Claim storage claim) {
claim = _claims[creatorContractAddress][instanceId];
require(claim.storageProtocol != StorageProtocol.INVALID, "Claim not initialized");
}
/**
* See {ILazyPayableClaim-checkMintIndex}.
*/
function checkMintIndex(address creatorContractAddress, uint256 instanceId, uint32 mintIndex) external override view returns(bool) {
Claim memory claim = getClaim(creatorContractAddress, instanceId);
return _checkMintIndex(creatorContractAddress, instanceId, claim.merkleRoot, mintIndex);
}
/**
* See {ILazyPayableClaim-checkMintIndices}.
*/
function checkMintIndices(address creatorContractAddress, uint256 instanceId, uint32[] calldata mintIndices) external override view returns(bool[] memory minted) {
Claim memory claim = getClaim(creatorContractAddress, instanceId);
uint256 mintIndicesLength = mintIndices.length;
minted = new bool[](mintIndices.length);
for (uint256 i; i < mintIndicesLength;) {
minted[i] = _checkMintIndex(creatorContractAddress, instanceId, claim.merkleRoot, mintIndices[i]);
unchecked{ ++i; }
}
}
/**
* See {ILazyPayableClaim-getTotalMints}.
*/
function getTotalMints(address minter, address creatorContractAddress, uint256 instanceId) external override view returns(uint32) {
Claim memory claim = getClaim(creatorContractAddress, instanceId);
return _getTotalMints(claim.walletMax, minter, creatorContractAddress, instanceId);
}
/**
* See {ILazyPayableClaim-mint}.
*/
function mint(address creatorContractAddress, uint256 instanceId, uint32 mintIndex, bytes32[] calldata merkleProof, address mintFor) external payable override {
Claim storage claim = _getClaim(creatorContractAddress, instanceId);
// Check totalMax
require(++claim.total <= claim.totalMax || claim.totalMax == 0, "Maximum tokens already minted for this claim");
// Validate mint
_validateMint(creatorContractAddress, instanceId, claim.startDate, claim.endDate, claim.walletMax, claim.merkleRoot, mintIndex, merkleProof, mintFor);
// Transfer funds
_transferFunds(claim.erc20, claim.cost, claim.paymentReceiver, 1, claim.merkleRoot != "");
// Do mint
address[] memory recipients = new address[](1);
recipients[0] = msg.sender;
uint256[] memory amounts = new uint256[](1);
amounts[0] = 1;
_mintClaim(creatorContractAddress, claim, recipients, amounts);
emit ClaimMint(creatorContractAddress, instanceId);
}
/**
* See {ILazyPayableClaim-mintBatch}.
*/
function mintBatch(address creatorContractAddress, uint256 instanceId, uint16 mintCount, uint32[] calldata mintIndices, bytes32[][] calldata merkleProofs, address mintFor) external payable override {
Claim storage claim = _getClaim(creatorContractAddress, instanceId);
// Check totalMax
claim.total += mintCount;
require(claim.totalMax == 0 || claim.total <= claim.totalMax, "Too many requested for this claim");
// Validate mint
_validateMint(creatorContractAddress, instanceId, claim.startDate, claim.endDate, claim.walletMax, claim.merkleRoot, mintCount, mintIndices, merkleProofs, mintFor);
// Transfer funds
_transferFunds(claim.erc20, claim.cost, claim.paymentReceiver, mintCount, claim.merkleRoot != "");
// Do mint
address[] memory recipients = new address[](1);
recipients[0] = msg.sender;
uint256[] memory amounts = new uint256[](1);
amounts[0] = mintCount;
_mintClaim(creatorContractAddress, claim, recipients, amounts);
emit ClaimMintBatch(creatorContractAddress, instanceId, mintCount);
}
/**
* See {ILazyPayableClaim-mintProxy}.
*/
function mintProxy(address creatorContractAddress, uint256 instanceId, uint16 mintCount, uint32[] calldata mintIndices, bytes32[][] calldata merkleProofs, address mintFor) external payable override {
Claim storage claim = _getClaim(creatorContractAddress, instanceId);
// Check totalMax
claim.total += mintCount;
require(claim.totalMax == 0 || claim.total <= claim.totalMax, "Too many requested for this claim");
// Validate mint
_validateMintProxy(creatorContractAddress, instanceId, claim.startDate, claim.endDate, claim.walletMax, claim.merkleRoot, mintCount, mintIndices, merkleProofs, mintFor);
// Transfer funds
_transferFundsProxy(claim.erc20, claim.cost, claim.paymentReceiver, mintCount, claim.merkleRoot != "");
// Do mint
address[] memory recipients = new address[](1);
recipients[0] = mintFor;
uint256[] memory amounts = new uint256[](1);
amounts[0] = mintCount;
_mintClaim(creatorContractAddress, claim, recipients, amounts);
emit ClaimMintProxy(creatorContractAddress, instanceId, mintCount, msg.sender, mintFor);
}
/**
* See {IERC1155LazyPayableClaim-airdrop}.
*/
function airdrop(address creatorContractAddress, uint256 instanceId, address[] calldata recipients,
uint256[] calldata amounts) external override creatorAdminRequired(creatorContractAddress) {
require(recipients.length == amounts.length, "Unequal number of recipients and amounts provided");
// Fetch the claim
Claim storage claim = _claims[creatorContractAddress][instanceId];
uint256 totalAmount;
for (uint256 i; i < amounts.length;) {
totalAmount += amounts[i];
unchecked{ ++i; }
}
require(totalAmount <= MAX_UINT_32, "Too many requested");
claim.total += uint32(totalAmount);
if (claim.totalMax != 0 && claim.total > claim.totalMax) {
claim.totalMax = claim.total;
}
// Airdrop the tokens
_mintClaim(creatorContractAddress, claim, recipients, amounts);
}
/**
* Mint a claim
*/
function _mintClaim(address creatorContractAddress, Claim storage claim, address[] memory recipients, uint256[] memory amounts) private {
uint256[] memory tokenIds = new uint256[](1);
tokenIds[0] = claim.tokenId;
IERC1155CreatorCore(creatorContractAddress).mintExtensionExisting(recipients, tokenIds, amounts);
}
/**
* See {ICreatorExtensionTokenURI-tokenURI}.
*/
function tokenURI(address creatorContractAddress, uint256 tokenId) external override view returns(string memory uri) {
uint224 tokenClaim = uint224(_claimTokenIds[creatorContractAddress][tokenId]);
require(tokenClaim > 0, "Token does not exist");
Claim memory claim = _claims[creatorContractAddress][tokenClaim];
string memory prefix = "";
if (claim.storageProtocol == StorageProtocol.ARWEAVE) {
prefix = ARWEAVE_PREFIX;
} else if (claim.storageProtocol == StorageProtocol.IPFS) {
prefix = IPFS_PREFIX;
}
uri = string(abi.encodePacked(prefix, claim.location));
}
}
| 25,707
|
9
|
// Adds a yield yak token, to allow withdrawing yak The address of the yak /
|
function addYakStrat(address yak) public onlyOwner {
require(yak != address(0), 'Cannot add a yakStrat with zero address');
yakStrats.push(yak);
}
|
function addYakStrat(address yak) public onlyOwner {
require(yak != address(0), 'Cannot add a yakStrat with zero address');
yakStrats.push(yak);
}
| 2,259
|
16
|
// Buy NFTs from a listing. _listingId The ID of the listing to update._buyFor The recipient of the NFTs being bought._quantity The quantity of NFTs to buy from the listing._currency The currency to use to pay for NFTs._expectedTotalPrice The expected total price to pay for the NFTs being bought. /
|
function buyFromListing(
|
function buyFromListing(
| 31,127
|
63
|
// called by the ceo to unpause, returns to normal state /
|
function unpause() onlyCEO whenPaused public {
paused = false;
emit Unpause();
}
|
function unpause() onlyCEO whenPaused public {
paused = false;
emit Unpause();
}
| 8,110
|
14
|
// Accepts a bid for a land/Gets approval for the contract to do so/tokenId The id of the land/minPrice The minimum accepted price, in Wei
|
function acceptBidForLand(uint tokenId, uint minPrice) external {
approve(address(auctionContract), tokenId);
auctionContract.acceptBidForLand(tokenId, minPrice);
}
|
function acceptBidForLand(uint tokenId, uint minPrice) external {
approve(address(auctionContract), tokenId);
auctionContract.acceptBidForLand(tokenId, minPrice);
}
| 22,408
|
11
|
// A Burnable Token Tavit Ohanian Token manager can burn tokens during migration /
|
contract BurnableToken is MintableToken {
using SafeMath for uint256;
/**
* @dev State definitions
*/
/**
* @dev Event definitions
*/
/**
* @notice token burn event
* @param burner who burned the tokens
* @param owner who was the owner of the tokens
* @param amount amount of tokens burned
*/
event TokenBurn(address indexed burner, address indexed owner, uint256 amount);
/**
* @dev Constructor
*/
/**
* @dev Fallback function (if exists)
*/
/**
* @dev External functions
*/
/**
* @dev Public functions
*/
/**
* @dev Administrative functions
*/
/**
* @notice burnTokens(address _owner)
* @notice Use to burn migrated tokens.
* @notice Migration manager has exclusive priveleges to burn older version tokens.
* @notice Available only during migration phase.
* @param _owner Address of token owner whose migrated tokens are to be burned.
*/
function burnTokens(address _owner) public onlyMigrationManager onlyWhenMigrating {
uint256 tokens = balances[_owner];
require(tokens > 0);
balances[_owner] = 0;
totalSupply = totalSupply.sub(tokens);
TokenBurn(msg.sender, _owner, tokens);
// Automatically switch phase when migration is done.
if(totalSupply == 0) {
// onlyTokenManager (not MigrationManager) may call setPhase()
//setPhase(Phase.Migrated);
currentPhase = Phase.Migrated;
LogPhaseSwitch(Phase.Migrated);
}
}
/**
* @dev Internal functions
*/
/**
* @dev Private functions
*/
}
|
contract BurnableToken is MintableToken {
using SafeMath for uint256;
/**
* @dev State definitions
*/
/**
* @dev Event definitions
*/
/**
* @notice token burn event
* @param burner who burned the tokens
* @param owner who was the owner of the tokens
* @param amount amount of tokens burned
*/
event TokenBurn(address indexed burner, address indexed owner, uint256 amount);
/**
* @dev Constructor
*/
/**
* @dev Fallback function (if exists)
*/
/**
* @dev External functions
*/
/**
* @dev Public functions
*/
/**
* @dev Administrative functions
*/
/**
* @notice burnTokens(address _owner)
* @notice Use to burn migrated tokens.
* @notice Migration manager has exclusive priveleges to burn older version tokens.
* @notice Available only during migration phase.
* @param _owner Address of token owner whose migrated tokens are to be burned.
*/
function burnTokens(address _owner) public onlyMigrationManager onlyWhenMigrating {
uint256 tokens = balances[_owner];
require(tokens > 0);
balances[_owner] = 0;
totalSupply = totalSupply.sub(tokens);
TokenBurn(msg.sender, _owner, tokens);
// Automatically switch phase when migration is done.
if(totalSupply == 0) {
// onlyTokenManager (not MigrationManager) may call setPhase()
//setPhase(Phase.Migrated);
currentPhase = Phase.Migrated;
LogPhaseSwitch(Phase.Migrated);
}
}
/**
* @dev Internal functions
*/
/**
* @dev Private functions
*/
}
| 18,009
|
6
|
// ---------------------------------------------------------------------------- ERC Token Standard 20 Interface https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md ----------------------------------------------------------------------------
|
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
|
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
| 3,541
|
101
|
// internal method for registering an interface /
|
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
|
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
| 10,191
|
94
|
// Calculate interest fee on earning from Compound and transfer fee to fee collector.Deposit available collateral from pool into Compound.Anyone can call it except when paused. /
|
function rebalance() external override live {
_rebalanceEarned();
uint256 balance = collateralToken.balanceOf(pool);
if (balance != 0) {
_deposit(balance);
}
}
|
function rebalance() external override live {
_rebalanceEarned();
uint256 balance = collateralToken.balanceOf(pool);
if (balance != 0) {
_deposit(balance);
}
}
| 51,900
|
263
|
// reference to the token (HATE) that all funds will be swapped into
|
address public immutable HATE;
|
address public immutable HATE;
| 11,046
|
203
|
// Update Base URI post deployment of smart contract
|
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
emit BaseURIChanged(baseURI);
}
|
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
emit BaseURIChanged(baseURI);
}
| 66,671
|
8
|
// Emitted when the maximum boost multiplier is changed/_maxBoost The maximum boost multiplier
|
event MaxBoostChange(uint256 _maxBoost);
|
event MaxBoostChange(uint256 _maxBoost);
| 27,071
|
80
|
// Returns the percent of the transfer fee. /
|
function feesPercent() public view returns (uint256) {
return _transferFees;
}
|
function feesPercent() public view returns (uint256) {
return _transferFees;
}
| 41,494
|
14
|
// The additions here will revert on overflow.
|
_totalSupply = _totalSupply + value;
_balances[account] = _balances[account] + value;
emit Transfer(address(0), account, value);
|
_totalSupply = _totalSupply + value;
_balances[account] = _balances[account] + value;
emit Transfer(address(0), account, value);
| 22,906
|
26
|
// Lets a publisher unpublish a contract and all its versions.
|
function unpublishContract(address _publisher, string memory _contractId)
external
onlyPublisher(_publisher)
onlyUnpausedOrAdmin
|
function unpublishContract(address _publisher, string memory _contractId)
external
onlyPublisher(_publisher)
onlyUnpausedOrAdmin
| 19,733
|
4,316
|
// 2159
|
entry "smart-arsed" : ENG_ADJECTIVE
|
entry "smart-arsed" : ENG_ADJECTIVE
| 18,771
|
17
|
// Function transfers tokens from one address to another._from is the address which you want to send tokens from._to is the address which you want to transfer to._value is the amout of tokens to be transfered./
|
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
|
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
| 54,981
|
39
|
// Transfer token to a specified address to The address to transfer to. value The amount to be transferred. /
|
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
|
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
| 24,700
|
211
|
// Returns true if `user` has approved `relayer` to act as a relayer for them. /
|
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
|
function hasApprovedRelayer(address user, address relayer) external view returns (bool);
| 33,492
|
156
|
// Extension of {AccessControl} that allows enumerating the members of each role. /
|
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
|
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
| 57,097
|
18
|
// internal Views //Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned._key The key of the tree to get the leaves from._cursor The pagination cursor._count The number of items to return. return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. `O(n)` where `n` is the maximum number of nodes ever appended. /
|
function queryLeafs(
SortitionSumTrees storage self,
bytes32 _key,
uint _cursor,
uint _count
|
function queryLeafs(
SortitionSumTrees storage self,
bytes32 _key,
uint _cursor,
uint _count
| 7,652
|
5
|
// SafeMathMath operations with safety checks that revert on error/
|
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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;
}
}
|
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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;
}
}
| 18,010
|
50
|
// Load consideration item typehash from runtime and place on stack.
|
bytes32 typeHash = _CONSIDERATION_ITEM_TYPEHASH;
|
bytes32 typeHash = _CONSIDERATION_ITEM_TYPEHASH;
| 33,392
|
25
|
// returns the token uri depending if the metadatas has been revealed or not
|
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (statusReveal == false) {
return hiddenURI;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
|
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (statusReveal == false) {
return hiddenURI;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
| 13,290
|
56
|
// Withdraws all the asset to the vault /
|
function withdrawAllToVault() public restricted {
if (address(rewardPool()) != address(0)) {
exitRewardPool();
}
_liquidateReward();
IERC20(underlying()).safeTransfer(
vault(),
IERC20(underlying()).balanceOf(address(this))
);
}
|
function withdrawAllToVault() public restricted {
if (address(rewardPool()) != address(0)) {
exitRewardPool();
}
_liquidateReward();
IERC20(underlying()).safeTransfer(
vault(),
IERC20(underlying()).balanceOf(address(this))
);
}
| 38,509
|
147
|
// VIEW INTERFACE //View function to see pending DHVs on frontend./_pid Pool's id/_user Address to check/ return amounts Amounts of reward tokens available to claim
|
function pendingRewards(uint256 _pid, address _user) external view hasPool(_pid) returns (uint256[] memory amounts) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
amounts = new uint256[](pool.rewardsTokens.length);
for (uint256 i = 0; i < pool.rewardsTokens.length; i++) {
uint256 accumulatedPerShare = pool.accumulatedPerShare[i];
if (block.number > pool.lastRewardBlock && pool.poolSupply != 0) {
uint256 blocks = block.number - pool.lastRewardBlock;
uint256 unaccountedReward = pool.rewardsPerBlock[i] * blocks;
accumulatedPerShare = accumulatedPerShare + (unaccountedReward * pool.accuracy[i]) / pool.poolSupply;
}
uint256 rewardsDebts = 0;
if (user.rewardsDebts.length > 0) {
rewardsDebts = user.rewardsDebts[i];
}
amounts[i] = (user.amount * accumulatedPerShare) / pool.accuracy[i] - rewardsDebts;
}
}
|
function pendingRewards(uint256 _pid, address _user) external view hasPool(_pid) returns (uint256[] memory amounts) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo memory user = userInfo[_pid][_user];
amounts = new uint256[](pool.rewardsTokens.length);
for (uint256 i = 0; i < pool.rewardsTokens.length; i++) {
uint256 accumulatedPerShare = pool.accumulatedPerShare[i];
if (block.number > pool.lastRewardBlock && pool.poolSupply != 0) {
uint256 blocks = block.number - pool.lastRewardBlock;
uint256 unaccountedReward = pool.rewardsPerBlock[i] * blocks;
accumulatedPerShare = accumulatedPerShare + (unaccountedReward * pool.accuracy[i]) / pool.poolSupply;
}
uint256 rewardsDebts = 0;
if (user.rewardsDebts.length > 0) {
rewardsDebts = user.rewardsDebts[i];
}
amounts[i] = (user.amount * accumulatedPerShare) / pool.accuracy[i] - rewardsDebts;
}
}
| 74,566
|
7
|
// MetaTx function that allows a signer to claim a stamp for free_signature Signed message sent through the relayer_tokenId Gen0 stamp to be cloned and claimed_nonce Transaction nonce return uint tokenId corresponding to the claimed NFT/
|
function metaClaimStamp(bytes memory _signature, uint256 _tokenId, uint _nonce)
public
onlyOwner
|
function metaClaimStamp(bytes memory _signature, uint256 _tokenId, uint _nonce)
public
onlyOwner
| 4,278
|
27
|
// Emit Event
|
emit CoinMinted(msg.sender, backedTokenID, amount);
success = true;
|
emit CoinMinted(msg.sender, backedTokenID, amount);
success = true;
| 52,203
|
55
|
// exclude from the Max wallet balance
|
_isExcludedFromMaxWallet[owner()] = true;
_isExcludedFromMaxWallet[address(this)] = true;
_isExcludedFromMaxWallet[_marketingWalletAddress] = true;
|
_isExcludedFromMaxWallet[owner()] = true;
_isExcludedFromMaxWallet[address(this)] = true;
_isExcludedFromMaxWallet[_marketingWalletAddress] = true;
| 27,779
|
22
|
// converter features
|
uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0;
|
uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0;
| 23,690
|
94
|
// The maximum of `a` and `b`. a a FixedPoint. b a FixedPoint.return the maximum of `a` and `b`. /
|
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
|
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
| 39,856
|
176
|
// Every time a kitty gives birth counter is decremented.
|
pregnantKitties--;
|
pregnantKitties--;
| 14,639
|
13
|
// return Address of PriceOracle
|
function getPriceOracle() external view override returns (address) {
return _getAddress(PRICE_ORACLE); // T:[AP-5]
}
|
function getPriceOracle() external view override returns (address) {
return _getAddress(PRICE_ORACLE); // T:[AP-5]
}
| 30,360
|
236
|
// Send msg.sender's Gold to this contract.
|
if (goldContract.transferFrom(msg.sender, this, _amount)) {
|
if (goldContract.transferFrom(msg.sender, this, _amount)) {
| 36,321
|
7
|
// swap
|
CErc20 supplyCToken = CErc20(_supplyCToken);
TransferHelper.safeApprove(_reserve, router, _amount);
uniswapRouter.swapExactTokensForTokens(_amount, getEstimatedAmountsOut(_amount, _reserve, supplyCToken.underlying())[1], getPath(_reserve, supplyCToken.underlying()), address(this), block.timestamp);
|
CErc20 supplyCToken = CErc20(_supplyCToken);
TransferHelper.safeApprove(_reserve, router, _amount);
uniswapRouter.swapExactTokensForTokens(_amount, getEstimatedAmountsOut(_amount, _reserve, supplyCToken.underlying())[1], getPath(_reserve, supplyCToken.underlying()), address(this), block.timestamp);
| 33,175
|
69
|
// Controller | Vault role - withdraw should always return to Vault
|
function withdraw(uint256) external;
|
function withdraw(uint256) external;
| 15,243
|
6
|
// Returns the timestamp when the last fee was collected/_symbol Desired token last fee withdrawal date
|
function getLastFeeWithdrawalDate(
bytes32 _symbol
|
function getLastFeeWithdrawalDate(
bytes32 _symbol
| 28,258
|
47
|
// For tokens that are burned and reminted, we don't track the creator, so zero royalties.
|
return (_NULL_ADDRESS, 0);
|
return (_NULL_ADDRESS, 0);
| 44,322
|
456
|
// the Metadata extension, but not including the Enumerable extension, which is available separately as
|
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @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.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
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");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).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;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
|
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @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.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
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");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).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;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
| 425
|
79
|
// Get NNIncome contract address/ return NNIncome contract address
|
function getNnIncomeAddress() external view returns (address);
|
function getNnIncomeAddress() external view returns (address);
| 9,083
|
30
|
// `transfer`. {sendValue} removes this limitation.taken to not create reentrancy vulnerabilities. Consider using{ReentrancyGuard} or the /
|
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
|
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
| 14,546
|
16
|
// Pool ID => (User ID => (Reward Id => Reward Info))
|
mapping (uint => mapping(address => mapping(uint => UserRewardInfo))) poolUserRewardInfo;
using SafeMath for uint;
using SafeERC20 for IERC20;
|
mapping (uint => mapping(address => mapping(uint => UserRewardInfo))) poolUserRewardInfo;
using SafeMath for uint;
using SafeERC20 for IERC20;
| 23,653
|
9
|
// Withdraws all LP tokens a user has staked. /
|
function exit() external;
|
function exit() external;
| 662
|
74
|
// Transfers CDP to the dst proxy
|
give(manager, cdp, proxy);
|
give(manager, cdp, proxy);
| 53,596
|
0
|
// Contract Variables and events
|
uint public minimumQuorum; // minimum quorum defined as an absolute number of voters
int public majorityMargin; // the margin of necessary majority defined as an absolute number of voters
Proposal[] public proposals; // dynamic array of Proposal objects
uint public numProposals; // proposal counter
|
uint public minimumQuorum; // minimum quorum defined as an absolute number of voters
int public majorityMargin; // the margin of necessary majority defined as an absolute number of voters
Proposal[] public proposals; // dynamic array of Proposal objects
uint public numProposals; // proposal counter
| 8,638
|
86
|
// Increment payments missed.
|
Loans[_loanID].Loan_Info.Payments_Missed++;
|
Loans[_loanID].Loan_Info.Payments_Missed++;
| 18,952
|
72
|
// Redeem init from the initial config.
|
uint256 public immutable redeemInit;
|
uint256 public immutable redeemInit;
| 33,433
|
176
|
// get underlying asset price for short option
|
FPI.FixedPointInt memory shortUnderlyingPrice = FPI.fromScaledUint(
oracle.getPrice(_vaultDetails.shortUnderlyingAsset),
BASE
);
|
FPI.FixedPointInt memory shortUnderlyingPrice = FPI.fromScaledUint(
oracle.getPrice(_vaultDetails.shortUnderlyingAsset),
BASE
);
| 67,531
|
57
|
// Divide a scalar by an Exp, returning a new Exp. /
|
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
|
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
| 16,662
|
188
|
// array with last balance recorded for each gov tokens
|
mapping (address => uint256) public govTokensLastBalances;
|
mapping (address => uint256) public govTokensLastBalances;
| 22,468
|
241
|
// Get reserve the assets are stored in/_nftId The NFT ID/ return The reserve address these assets are stored in
|
function getAssetReserve(uint256 _nftId) external view returns (address) {
return records[_nftId].reserve;
}
|
function getAssetReserve(uint256 _nftId) external view returns (address) {
return records[_nftId].reserve;
}
| 60,325
|
10
|
// user can request some tokens for testing amount the amount of tokens to be requestedreturn valid Boolean indication of tokens are requested /
|
function requestTokens(
uint256 amount
)
external
isValidAddress(msg.sender)
returns (bool tokensTransferred)
|
function requestTokens(
uint256 amount
)
external
isValidAddress(msg.sender)
returns (bool tokensTransferred)
| 19,874
|
78
|
// Send the funds to gambler.
|
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
|
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
| 13,498
|
3
|
// [H100a]
|
bytes32[] memory proposalHash,
|
bytes32[] memory proposalHash,
| 50,610
|
204
|
// Find facet for function that is called and execute the function if a facet is found and return any value.
|
fallback() external payable {
LibDiamond.DiamondStorage storage ds;
bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
address facet = address(bytes20(ds.facets[msg.sig]));
require(facet != address(0), "Diamond: Function does not exist");
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
|
fallback() external payable {
LibDiamond.DiamondStorage storage ds;
bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
address facet = address(bytes20(ds.facets[msg.sig]));
require(facet != address(0), "Diamond: Function does not exist");
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
| 4,412
|
58
|
// @inheritdoc IERC20Metadata /
|
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
|
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
| 7,267
|
36
|
// create assertion with scc state batchvmHash New VM hash. inboxSize Size of inbox corresponding to assertion (number of transactions). _batch Batch of state roots. _shouldStartAtElement Index of the element at which this batch should start. _signature tss group signature of state batches. /
|
function createAssertionWithStateBatch(
|
function createAssertionWithStateBatch(
| 11,260
|
47
|
// failed to reach supermajority, refund expert bids and split bounty
|
for (j = 0; j < assertions.length; j++) {
expertRewards[j] = expertRewards[j].add(assertions[j].bid);
expertRewards[j] = expertRewards[j].add(bounty.amount.div(assertions.length));
}
|
for (j = 0; j < assertions.length; j++) {
expertRewards[j] = expertRewards[j].add(assertions[j].bid);
expertRewards[j] = expertRewards[j].add(bounty.amount.div(assertions.length));
}
| 44,950
|
117
|
// Deposit collateral token into lending pool. _amount Amount of collateral token /
|
function deposit(uint256 _amount) public override onlyKeeper {
_updatePendingFee();
_deposit(_amount);
}
|
function deposit(uint256 _amount) public override onlyKeeper {
_updatePendingFee();
_deposit(_amount);
}
| 38,508
|
2
|
// Internal function to provide the address of the implementation contract/
|
function _implementation() internal view returns(address) {
return __implementation;
}
|
function _implementation() internal view returns(address) {
return __implementation;
}
| 42,629
|
13
|
// Unstakes a token and records the start block number or time stamp. /
|
function unstake(uint256 tokenId) public {
require(
IERC721NES(tokenContract).ownerOf(tokenId) == msg.sender,
"You are not the owner of this token"
);
require(
IERC721NES(tokenContract).isStaked(tokenId) == true,
"Token is not staked"
);
require(!stakingPaused, "Unstaking is currently paused");
tokenToTotalDurationStaked[tokenId] += getCurrentAdditionalBalance(
tokenId
);
IERC721NES(tokenContract).unstakeFromController(tokenId, msg.sender);
}
|
function unstake(uint256 tokenId) public {
require(
IERC721NES(tokenContract).ownerOf(tokenId) == msg.sender,
"You are not the owner of this token"
);
require(
IERC721NES(tokenContract).isStaked(tokenId) == true,
"Token is not staked"
);
require(!stakingPaused, "Unstaking is currently paused");
tokenToTotalDurationStaked[tokenId] += getCurrentAdditionalBalance(
tokenId
);
IERC721NES(tokenContract).unstakeFromController(tokenId, msg.sender);
}
| 6,194
|
17
|
// The addresses preassigned the `escapeHatchCaller` role/is the only addresses that can call a function with this modifier
|
modifier onlyEscapeHatchCaller {
require (msg.sender == escapeHatchCaller);
_;
}
|
modifier onlyEscapeHatchCaller {
require (msg.sender == escapeHatchCaller);
_;
}
| 11,890
|
10
|
// require(_value <= balanceOf(_deposit));
|
frozenAccounts[_wallet] = _freeze;
uint256 _frozen = accounts[_wallet].frozen;
uint256 _balance = accounts[_wallet].balance;
uint256 freezeAble = _balance.sub(_frozen);
if (_freeze) {
if (_value > freezeAble) {
_value = freezeAble;
}
|
frozenAccounts[_wallet] = _freeze;
uint256 _frozen = accounts[_wallet].frozen;
uint256 _balance = accounts[_wallet].balance;
uint256 freezeAble = _balance.sub(_frozen);
if (_freeze) {
if (_value > freezeAble) {
_value = freezeAble;
}
| 20,877
|
52
|
// Check if item is in use
|
if (getItemsInUseByToken[tokenID][i] > 0) {
|
if (getItemsInUseByToken[tokenID][i] > 0) {
| 21,367
|
85
|
// Send funds to multisig account, and emit a SwapToken event for emission to the Secret Network_recipient: The intended recipient's Secret Network address._amount: The amount of ENG tokens to be itemized._tokenAddress: The address of the token being swapped_toSCRT: Amount of SCRT to be minted - will be deducted from the amount swapped/
|
function swapToken(bytes memory _recipient, uint256 _amount, address _tokenAddress, uint256 _toSCRT)
public
notPaused()
tokenWhitelisted(_tokenAddress)
isSecretAddress(_recipient)
isNotGoingAboveLimit(_tokenAddress, _amount)
|
function swapToken(bytes memory _recipient, uint256 _amount, address _tokenAddress, uint256 _toSCRT)
public
notPaused()
tokenWhitelisted(_tokenAddress)
isSecretAddress(_recipient)
isNotGoingAboveLimit(_tokenAddress, _amount)
| 15,124
|
58
|
// Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Returns the name of the token. /
|
function name() public virtual pure returns (string memory);
|
function name() public virtual pure returns (string memory);
| 39,591
|
168
|
// We call doTransferIn for the payer and the repayAmount Note: The aToken must handle variations between ERC-20 and ETH underlying. On success, the aToken holds an additional repayAmount of cash. If doTransferIn fails despite the fact we checked pre-conditions,we revert because we can't be sure if side effects occurred. /
|
vars.err = doTransferIn(payer, vars.repayAmount);
require(vars.err == Error.NO_ERROR, "repay borrow transfer in failed");
|
vars.err = doTransferIn(payer, vars.repayAmount);
require(vars.err == Error.NO_ERROR, "repay borrow transfer in failed");
| 9,274
|
111
|
// Equivalent to `_safeMint(to, quantity, '')`. /
|
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
|
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
| 27,116
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.